C ++自定义放置新的和放置删除的调用 [英] c++ self-defined placement new and placement delete invoking

查看:95
本文介绍了C ++自定义放置新的和放置删除的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义我自己的展示位置新内容和展示位置删除(带有额外的参数),我发现我可以正确调用该展示位置,而我却无法访问该展示位置删除.谁能告诉我我定义的展示位置删除不正确还是调用不正确?

I want to define my own placement new and placement delete(taking extra parameters), and I found I could invoke the placement correctly, while I couldn't access the placement delete. Could anyone tell me whether I define the placement delete incorrectly or I invoke it incorrectly?

class A
{
public:
    A( int a ) : a(a){}

    static void* operator new( std::size_t, int ); // the placement new
    static void operator delete( void*, int )throw(); // the corresponding placement delete
private:
    int a;
};

void* A::operator new( std::size_t size, int n )
{
    std::cout << "size: " << size << "  " << "n: " << n << std::endl;
    return ::operator new(size);
}

void A::operator delete( void* p, int n )throw()
{
    std::cout << "n: " << n << std::endl;
    ::operator delete(p);
}

int main( int argc, char* argv[] )
{
    A* a = new(10) A(100);

    std::cout << std::endl;

    delete(4) a; // error???????????????????, but how?

    return 0;
}

推荐答案

Placement delete仅可用于处理在评估Placement new表达式期间发生的异常.如果构建成功完成,则以后将使用正常的delete.

Placement delete is available only to handle exceptions which occur during evaluation of a placement new expression. If construction finishes successfully, then later on normal delete will be used.

您可以显式调用放置释放函数,但它的行为与delete运算符不同(不会自动调用析构函数).

You can call a placement deallocation function explicitly, but it won't have the same behavior as the delete operator (it won't call the destructor automatically).

在您的情况下,相应的代码为:

In your case, the corresponding code would be:

a->~A();
A::operator delete(a, 4);

好吧!

对于数组,情况甚至更糟,因为您无法从编译器供其自身使用的位置存储元素的数量(以及要调用的析构函数的数量).

For arrays it is even worse, because you can't retrieve the number of elements (and number of destructors to call) from the location where the compiler stored that for its own use.

设计重载的operator new,使其与一个参数operator delete正确配对.然后,您班上的用户可以使用delete ptr;std::unique_ptr等.

Design your overloaded operator new so that it pairs correctly with one-argument operator delete. Then users of your class can use delete ptr; and std::unique_ptr etc.

如果您确实需要自定义解除分配,则返回std::shared_ptr并带有自定义删除器的分配包装器将比自定义放置新的更好.

If you do require custom deallocation, then an allocation wrapper which returns std::shared_ptr with a custom deleter will be better than custom placement new.

这篇关于C ++自定义放置新的和放置删除的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆