简体   繁体   中英

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?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM