overloading new and delete operator with optional arguments
Asked Answered
H

1

7
#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?

Haversine answered 21/11, 2012 at 23:46 Comment(1)
There is no placement-delete expression in C++. You need to destroy the object manually.Stemma
Z
8

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));
}
Zoan answered 21/11, 2012 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.