gpt4 book ai didi

c++ - 即使在同一类型上,是否应该使用 placement new 调用析构函数

转载 作者:太空狗 更新时间:2023-10-29 20:50:19 24 4
gpt4 key购买 nike

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

输出

2
destroyed

我所知道的是,在使用 placement new 时应该始终调用析构函数。但是,在此示例代码中,析构函数在 main 的末尾被隐式调用,因此我认为再次调用它是未定义的行为。所以现在我想知道在使用 placement new 时是否应该始终调用析构函数,或者在某些情况下不应调用析构函数?

最佳答案

在C++标准中有明确规定

[basic.life]

5 A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

关于未定义行为的可能性,最后一句话留下了一点回旋余地1。但最终,唯一定义明确的类型是析构函数真正微不足道的类型。


<子>1 - 无论如何,截至撰写本文时。

关于c++ - 即使在同一类型上,是否应该使用 placement new 调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55225263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com