#include <new>
struct X
{
~X() { std::cout << "destroyed" << std::endl; }
int x;
};
int main(int argc, const char * const * const argv)
{
X x{1};
new (&x) X{2};
std::cout << x.x << std::endl;
return 0;
}
Output
2
destroyed
我所知道的是,当使用放置 new 时,应该始终调用析构函数。然而,在此示例代码中,析构函数在主函数末尾隐式调用,因此我认为再次调用它是未定义的行为。
所以现在我想知道在使用placement new时是否应该始终调用析构函数,或者是否存在某些条件下不应调用析构函数?
它在 C++ 标准中明确指定
[基本生活]
5 https://timsong-cpp.github.io/cppwp/n4659/basic.life#5程序可以通过重用对象来结束任何对象的生命周期
对象占用的存储空间或通过显式调用
具有非平凡类类型的对象的析构函数
析构函数。对于具有非平凡的类类型的对象
析构函数,程序不需要调用析构函数
在重用对象占用的存储之前明确地或
释放;但是,如果没有显式调用析构函数或
如果不使用删除表达式来释放存储,则
析构函数不应被隐式调用,并且任何依赖于析构函数的程序
析构函数产生的副作用具有未定义的行为。
The last sentence leaves a little bit of wriggle room regarding the possibility of undefined behavior1. But ultimately, the only types for which this is well-defined are those for which the destructor is truly trivial.
1 - As of writing this, anyway.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)