c++ - 为什么在 C++11 中不删除具有副作用未定义行为的析构函数的对象?

标签 c++ memory-leaks c++11 destructor undefined-behavior

This answer引用 C++11 标准 3.8:

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.

关于析构函数不被调用的部分很清楚。现在假设跳过的析构函数有一个副作用,应该会影响程序的行为。

为什么程序行为现在未定义?为什么不跳过副作用(因为未调用析构函数)并且程序在没有应用副作用的情况下正常运行?

最佳答案

重要的部分是该段的第一部分(强调我的):

A program may end the lifetime of any object by reusing the storage which the object occupies ...

如果您简单地为一个调用其析构函数的对象重用存储,那么您会得到未定义的行为。例如,该对象可能已经启动了一个线程,或者注册了一个回调,或者外部组件可能希望该对象仍然存在的一些其他操作。

关于c++ - 为什么在 C++11 中不删除具有副作用未定义行为的析构函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9971559/

相关文章:

C++ 和可能的硬件故障

c++ - 在当前类的构造函数中调用其他类定义的虚函数

c++ - 编译器对析构函数省略的自由度是多少?

c++ - std::atomic_flag 静态初始化线程在 Visual Studio 2012 中是否安全?

c++ - 模板和重载决议

c++ - wstring 到 LPARAM 和 WPARAM

java - 有可用内存的 OutOfMemoryError

javascript - 获取 GC,在通过 webpack 捆绑时处理内存不足错误

iOS - 什么是分配泄漏?

c++ - 将 'std::initializer_list<int>' 转换为 'int'