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

2023-09-26C/C++开发问题
2

本文介绍了为什么不在 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 eects produced by the destructor has undened 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.

这篇关于为什么不在 C++11 中删除具有副作用未定义行为的析构函数的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6