【问题标题】:overloading new and delete operator with optional arguments使用可选参数重载 new 和 delete 运算符
【发布时间】:2012-11-10 07:58:28
【问题描述】:
#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++ 会释放一个带有附加参数的新对象,并匹配删除相同的参数,但我显然是错误的。

让上面的代码调用我的重载删除的正确方法是什么?

【问题讨论】:

  • C++ 中没有放置删除表达式。您需要手动销毁该对象。

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


【解决方案1】:

当您使用任何形式的放置 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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 2014-03-26
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多