开发者

Something unclear with operator delete

I am new to C++ and I have something unclear:

#include <iostream>
using namespace std;

double* foo(void)
{
    double* b = new double[100];
    return b;
}

int 开发者_C百科main()
{
    double* a = foo();

    delete [] a;
    return 0;
}

Is there something wrong with this code? I mean whether the way I use operator delete is right? I assign the pointer b which points to the allocated memory in foo function to pointer a outside foo, can I release memory by means of delete[]a in main? I don't have any idea how does the compiler calculate the number of bytes to release when execute delete[]. Thanks


The code is correct (though not usually part of any well-written modern C++ program).

Dynamically allocated arrays are stored with hidden information about their size so that delete[] p knows how many elements to delete.


If you're curious about the details, you can rig up a little test class and take advantage of the member allocation operators:

struct ArrayMe
{
  static void * operator new[](size_t n) throw(std::bad_alloc)
  {
    void * p = ::operator new[](n);
    std::cout << "new[]ed " << n << " bytes at " << p << "." << std::endl;
    return p;
  }

  static void operator delete[](void * p, std::size_t n) throw()
  {
    std::cout << "delete[]ing " << n << " bytes at " << p << "." << std::endl;
    ::operator delete[](p);
  }

  double q;
};

Now say:

std::cout << "sizeof(ArrayMe) = " << sizeof(ArrayMe) << std::endl;
ArrayMe * const a = new ArrayMe[10];
delete[] a;


Call delete [] to delete C-style arrays allocated with operator new []. Delete [] will know how many bytes were allocated by operator new[].

Call delete to delete objects allocated with operator new (no brackets). Never, ever mix them! I.e. never call delete [] on something allocated with operator new, and never call delete on something allocated with operator new [].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜