I’ve been reading about overloading new and delete (and related topics like placement new/delete). One thing that is confusing me thus far is that operator delete’s standard signature is (at class-scope):
void operator delete(void *rawMemory, std::size_t size) throw();
Delete is called like this:
MyClass* ptr = new MyClass;
delete ptr;
So, how does delete ptr; provide the second parameter for size? Also, can I assume that the MyClass* is implicitly converted to the void* in this circumstance?
Short Answer:
newanddeleteoperators are overloaded at class scope for optimizing allocation for objects of specific class. But there can be special scenarios due to certain beasts likeInheritancewhich may lead to allocation requests for more than the class size itself,Since the very purpose ofnewanddeleteoverload is special tuning for objects of sizesizeof(Base), nothing larger or smaller, these overloaded operators should forward all otherwrong sizedmemory requests to::operator newand::operator delete, to be able to do so, the size parameter needs to be passed as an parameter.Long Answer:
Consider a Special Scenario:
In the above sample, because of inheritance The derived class
Derivedinherits the new operator of theBaseclass. This makes calling operator new in a base class to allocate memory for an object of a derived class possible. The best way for our operator new to handle this situation is to divert such calls requesting the “wrong” amount of memory to the standard operator new, like this:While overloading the
deleteoperator, One must also ensure that since class-specific operator new forwards requests of the “wrong” size to::operator new, One MUST forward “wrongly sized” deletion requests to ::operator delete, Since the original operators are guaranteed to to handle these requests in a standard compliant manner.So the custom
deleteoperator will be something like this:Further Reading:
The following C++-Faq entry talks about overloading new and delete in a standard compliant way and might be a good read for you:
How should i write iso c++ standard conformant custom new and delete operators?