Overloading the new and delete operator with optional arguments

#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 

I thought C ++ would free the new'd object with additional arguments with its matching removal of the same arguments, but I was clearly wrong.

What is the correct way to get the code above to call my overloaded delete?

+7
source share
1 answer

If you use any form of placing new, except for versions of std::nothrow_t , you need to explicitly destroy the object and free its memory by any means that you consider necessary. However, an overloaded version of operator delete() must exist because it is used if building an object throws an exception! In this case, no pointer is returned since an exception is thrown. Therefore, memory disposal should be performed in this allocation process.

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)); } 
+8
source

All Articles