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

时间:2012-11-21 23:46:52

标签: c++ operator-overloading new-operator delete-operator

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

输出(via ideone):

my new 1

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

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

1 个答案:

答案 0 :(得分:8)

当您使用任何形式的placement new时,除了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));
}
相关问题