我们需要显式调用“简单POD类”的析构函数分配“placement new”? [英] Do we need to explicitly call the destructor for the "simple POD classes" allocated with "placement new"?

查看:151
本文介绍了我们需要显式调用“简单POD类”的析构函数分配“placement new”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的简单,我的意思是一个非虚拟空析构函数或POD类型的类。

Here by "simple", I mean a class with non-virtual empty destructor or POD type.

典型示例:

char buffer[SIZE];
T *p = new(buffer) T;
...
p->~T();  // <---- always ?

如果我们不在 p

What happens if we don't call the explicit destructor on p? I don't think it is undefined behavior or memory leak.
Is there any problem with reusing buffer ?

推荐答案

对于POD类型或具有平凡析构函数的类:no。当对象的存储器被释放或重用时,对象的生存期将结束。你不必显式地调用析构函数,如果你不想。

For a POD-type or a class with a trivial destructor: no. The lifetime of the object will end when the storage for the object is released or reused. You don't have to call the destructor explicitly if you don't want to.

也就是说,没有理由不去。对于一个具有简单析构函数的类型,析构函数调用不会生成任何代码。

That said, there's no reason not to. For a type with a trivial destructor the destructor call will generate no code.

如果一个具有空析构函数的类允许类有成员如果你的程序依赖于这些析构函数被调用,你可能得到未定义的行为。

If, by a class with an "empty" destructor you are allowing the possibility the class has members or base classes with non-trivial destructors then you may get undefined behaviour if your program relies on these destructors being called.

请注意,用户提供的析构函数是一个非平凡的即使它是非虚拟的并且是空的。尽管这样,你仍然被允许通过简单释放或重用它的存储器来结束一个对象的生命周期,只要你的程序不依赖于析构函数的任何副作用。 (见ISO / IEC 14882:2011的3.8 [basic.life] / 4)

Note that a user provided destructor is a non-trivial destructor even if it is non-virtual and is empty. Despite this you are still permitted to end the lifetime of an object with such a destructor by simply releasing or reusing its storage provided that your program doesn't depend on any side effects of the destructor. (See 3.8 [basic.life] / 4 of ISO/IEC 14882:2011)

这篇关于我们需要显式调用“简单POD类”的析构函数分配“placement new”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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