gpt4 book ai didi

c++ - UB是否可以重用对象的存储而不先破坏它?

转载 作者:IT老高 更新时间:2023-10-28 22:26:47 25 4
gpt4 key购买 nike

给定非 POD 类型 T:

auto p = new T();
::new (p) T();
/* ... */
delete p;

这是UB,对吧?

显然,我没有直接泄漏为第一个 T 分配的内存(如果它没有间接成员,那么我根本不会泄漏任何东西),但它从未被破坏,这在我看来,对于由有知觉的猫类生物居住的星系自发湮灭来说,这是一个很好的候选人。

感谢 @Xeo因为,嗯,在 C++ Lounge 中“启发”这个问题。

最佳答案

这取决于。

[C++11: 3.8/1]: The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

显然,这是一个重复使用的案例。

还有:

[C++11: 3.8/4]: 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 (5.3.5) 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.

因此,即使对于非 POD 类型 T,它也是有效的 iff 在您的程序中实际上没有任何东西依赖于析构函数正在做什么。

这有点空灵,但它确实可能允许你在做的事情。


请注意,这种宽大处理不会扩展到一些稍微奇怪的情况:

[C++11: 3.8/9]: Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior

关于c++ - UB是否可以重用对象的存储而不先破坏它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197636/

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