While reading answers to this question I noticed that answers (this for example) imply that operator delete
can be called even when delete
statement is executed on a null pointer.
So I wrote a small snippet:
class Test {
public:
void* operator new( size_t ) { /*doesn't matter*/ return 0; }
void operator delete( void* ptr ) {
ptr; //to suppress warning and have a line to put breakpoint on
}
};
int main()
{
Test* ptr = 0;
delete ptr;
}
and - surprisingly for me - Test::operator delete()
is invoked with ptr
holding a null pointer.
As I understand it operator new
allocates memory and operator delete
returns memory to the allocator. If I call delete
statement on a null pointer it means there was no object behind the pointer and there's no memory to return to the allocator.
delete
statement includes invoking a destructor. When I pass a null pointer the destructor is surely not invoked - C++ takes care of that. Then why is operator delete
invoked in this case?