为什么不在 C++11 中删除具有副作用未定义行为的析构函数的对象?
这个答案引用了 C++11 Standard 3.8:
This answer quotes C++11 Standard 3.8:
如果没有显式调用析构函数或者如果没有使用删除表达式(5.3.5)来释放存储,则不应隐式调用析构函数,任何依赖于由析构函数产生的副作用的程序析构函数有未定义的行为.
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 e?ects produced by the destructor has unde?ned behavior.
关于未调用析构函数的部分很清楚.现在假设跳过的析构函数有一个应该影响程序行为的副作用.
The part about the destructor not being called is clear. Now suppose the skipped destructor had a side effect that should have affected the program behavior.
为什么现在程序行为未定义?为什么不跳过副作用(因为没有调用析构函数)并且程序正常运行而没有应用副作用?
Why is the program behavior undefined now? Why wouldn't the side effects be skipped (since the destructor is not called) and the program run normally just without side effects applied?
推荐答案
重要的部分是那一段的第一部分(重点是我的):
The important part is the first part of that paragraph (emphasis mine):
程序可以通过重用对象占用的存储空间来结束任何对象的生命周期 ...
如果您只是将存储重用于其析构函数未被调用的对象,那么您会得到未定义的行为.例如,对象可能已经启动了一个线程,或者注册了一个回调,或者外部组件可能期望对象仍然存在的一些其他操作.
If you simply reuse the storage for an object whose destructor has not been called, then you get undefined behaviour. For example, the object could have started a thread, or registered a callback, or some other action where an external component might expect the object to still exist.
相关文章