为什么不删除在C ++ 11中具有带有副作用未定义行为的析构函数的对象? [英] Why is not deleting an object that has a destructor with a side effect undefined behavior in C++11?

查看:119
本文介绍了为什么不删除在C ++ 11中具有带有副作用未定义行为的析构函数的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此回答引用了C ++ 11标准版3.8:

This answer quotes C++11 Standard 3.8:

如果没有显式调用析构函数,或者如果没有使用delete-expression(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 effects produced by the destructor has undefined 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):


程序可能会终止任何对象的生命周期重复使用对象占用的存储

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

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

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中具有带有副作用未定义行为的析构函数的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆