delete a NULL pointer does not call overloaded delete when destructor is written
c++, destructor, memory-management
Solution
I remember something similar on operator delete a while ago in comp.lang.c++.moderated. I cannot find it now, but the answer stated something like this ..
Unfortunately, the language specification is not sufficiently clear on whether the control should go into the overloaded 'operator delete' when the delete-expression is invoked on the null-pointer of corresponding type, even though the standard does say that delete-expression on null-pointer is a no-op.
And James Kanze specifically said:
It's still the responisiblity of operator delete (or delete[]) to check; the standard doesn't guarantee that it won't be given a null pointer; the standard requires that it be a no-op if given a null pointer. Or that the implementation is allowed to call it. According to the latest draft, "The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect." I'm not quite sure what the implications of that "is one supplied in the standard library" are meant to be---taken literally, since his function is not one provided by the standard library, the sentence wouldn't seem to apply. But somehow, that doesn't make sense
I remember this becoz i had a similar prob sometime back and had preserved the answer in a .txt file.
UPDATE-1:
Oh i found it here. Also read this link defect report. So, the answer is Unspecified. Chapter 5.3.5/7.
Problem
``` class Widget { public: Widget() { cout<<"~Widget()"<<endl; } ~Widget() { cout<<"~Widget()"<<endl; } void* operator new(size_t sz) throw(bad_alloc) { cout<<"operator new"<<endl; throw bad_alloc(); } void operator delete(void *v) { cout<<"operator delete"<<endl; } }; int main() { Widget* w = 0; try { w = new Widget(); } catch(bad_alloc) { cout<<"Out of Memory"<<endl; } delete w; getch(); return 1; } ``` In this code, `delete w` does not call the overloaded `delete` operator when the destructor is there. If the destructor is omitted, the overloaded `delete` is called. Why is this so? Output when ~Widget() is written operator new Out of Memory Output when ~Widget() is not written operator new Out of Memory operator delete