#include <new>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
struct foo {};
inline void* operator new(size_t size, foo*) throw (std::bad_alloc)
{
std::cout << "my new " << size << std::endl;
return malloc(size);
}
inline void operator delete(void* p, foo*) throw()
{
std::cout << "my delete" << std::endl;
free(p);
}
int main()
{
delete new((foo*)NULL) foo;
}
Output (via ideone):
my new 1
My thinking was that C++ would free an object new'd with additional arguments with its matching delete of the same arguments, but I was obviously incorrect.
What is the correct way to get the code above to call my overloaded delete?
When you use any form of placement new, except for the std::nothrow_t
versions, you need to explicitly destroy the object and release its memory with whatever means you see fit. The overloaded version of operator delete()
is still required to exist, however, because it is used if construction of the object throws an exception! In this case, no pointer is returned because an exception is thrown. Getting rid of the memory has, thus, to be done in this process of allocation.
That is, you main()
should look something like this:
int main()
{
foo* p = new (static_cast<foo*>(0)) foo;
p->~foo();
operator delete(p, static_cast<foo*>(0));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With