使用可选参数重载 new 和 delete 运算符

overloading new and delete operator with optional arguments

本文关键字:new delete 运算符 重载 参数      更新时间:2023-10-16
#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;
}

输出(通过 ideone):

my new 1

我的想法是,C++会释放一个带有附加参数的新对象,并匹配删除相同的参数,但我显然是不正确的。

获取上述代码以调用重载删除的正确方法是什么?

当你使用任何形式的放置新时,除了std::nothrow_t版本,你需要显式销毁对象,并以你认为合适的任何方式释放它的内存。但是,operator delete() 的重载版本仍然需要存在,因为如果对象的构造引发异常,则会使用它!在这种情况下,不会返回任何指针,因为会引发异常。因此,在这个分配过程中必须摆脱内存。

也就是说,您main()应该看起来像这样:

int main()
{
    foo* p = new (static_cast<foo*>(0)) foo;
    p->~foo();
    operator delete(p, static_cast<foo*>(0));
}