Re: diff between user defined delete and delete[]
On Nov 17, 4:13 am, mail....@gmail.com wrote:
Suppose in a class we overload four operators:
operator new
operator delete
operator new[]
operator delete[]
class Test{
public:
void * operator new (size_t t){
cout<<"\nCalling... new";
return malloc(t);
}
void operator delete (void *p){
cout<<"\nCalling ... delete";
free(p);
}
void * operator new [] (size_t t){
cout<<"\nCalling ... new[]";
return malloc(t);
}
void operator delete [] (void *p){
cout<<"\nCalling ... delete[]";
free(p);
}
};
If we perform
Test *p=0; delete p;
It calls operator delete.
But if we perform
Test *p=0; delete []p;
It doesn't call operator delete[] until and unless we don't call
operator new[]. Means If we do like this;
Test *p=0; p=new Test[10]; delete[] p; It calls operator delete[].
Why???
The FAQ covers the subject. Read the 2 common techniques used with
primitive arrays
[16.14] After p = new Fred[n], how does the compiler know there are n
objects to be destructed during delete[] p?
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.14
Although in modern code unless there is a really good reason:
a) don't allocate on the heap manually, use smart pointers or RAII
b) prefer dynamic containers over primitive, fixed arrays
(std::vector, std::deque, etc)