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

标签 c++ memory-management c++11

给定非 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/

相关文章:

c++ - 自动类型推导中的 Const

c++ - 指向相同地址的空指针

c - C中用于内存分配/指针的星号定位

c++ - 如何创建函数指针数组?

C++ 类模板构造函数继承与指针

c++ - 如何在排序函数中使用 rbegin() ?

c++ - 基本类型和复杂类型的通用 for 循环

c++ - 为什么 std::unique_ptr 不允许类型推断?

c++ - 为什么 Adapter 会公开继承 Target 而私有(private)继承 Adapter?

Android:浅堆和保留堆有什么区别