Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading 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

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?

like image 994
Zach Saw Avatar asked Nov 21 '12 23:11

Zach Saw


1 Answers

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));
}
like image 165
Dietmar Kühl Avatar answered Oct 20 '22 09:10

Dietmar Kühl