In his book C++ Programming Language(4th ed), stroustroup has mentioned that the global operator new & delete can be overloaded by writing global functions with the following signatures:
void* operator new(size_t); // use for individual object
void* operator new[](size_t); // use for array
void operator delete(void*, size_t); // use for individual object
void operator delete[](void*, size_t); // use for array
NOTE: The size_t parameter is passed for the delete to determine the correct object size specifically when deleting a derived object pointed by a base pointer(base needs virtual dtor so that correct size is passed).
I was trying to overload the global versions for the individual object. The operator new works fine. The operator delete with the above signature works fine, but delete doesn't get called. If I change the delete signature so that it just takes a void *, it does get called. What could be the problem:
Here is code:
void * operator new (size_t size)
{
cout << "My operator new called\n";
auto p = malloc(size);
return p;
}
void operator delete (void * ptr, size_t size) // Removing size_t parameter makes it work
{
cout << "My operator delete called\n";
free(ptr);
}
Strange is also the fact that if I make the operator delete a member of a class so that its overloaded just for that class, both delete signatures(with size_t and without size_t) seem to work!
Passing size_t parameter in delete does seem logical as explained in the NOTE I had mentioned. But what could be the reason for this behavior? I am using VS2013 for testing out the examples.