C++核心准则E.16:析构函数,内存释放和swap操作永远不能失败
共 2585字,需浏览 6分钟
·
2020-08-04 17:10
E.16: Destructors, deallocation, and swap must never fail
E.16:析构函数,内存释放和swap操作永远不能失败
Reason(原因)
We don't know how to write reliable programs if a destructor, a swap, or a memory deallocation fails; that is, if it exits by an exception or simply doesn't perform its required action.
如果析构函数、swap操作或者内存释放失败了,我们不知道如何编写可信赖的处理程序;也就是说,如果它因为异常退出或者只是没有执行要求的操作。
Example, don't(反面示例)
class Connection {
// ...
public:
~Connection() // Don't: very bad destructor
{
if (cannot_disconnect()) throw I_give_up{information};
// ...
}
};
Note(注意)
Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close". To the best of our knowledge nobody has found a general way of doing this. Occasionally, for very specific examples, you can get away with setting some state for future cleanup. For example, we might put a socket that does not want to close on a "bad socket" list, to be examined by a regular sweep of the system state. Every example we have seen of this is error-prone, specialized, and often buggy.
为了编写违反本规则的可信赖代码示例进行了很多尝试,例如网络链接“拒绝关闭”。即使动作所有知识,也没有人发现这么做的通用方法。偶然情况下,对于非常特殊的情况,你可以通过设定在将来清除处理时使用的某些状态。例如我们可以将不想关闭的socket放入一个“坏socket”列表中,以便用正规的系统状态清除程序进行检查。我们看到的所有相关示例都是容易出错的,特殊的,通常也有很多bug。
Note(注意)
The standard library assumes that destructors, deallocation functions (e.g., operator delete), and swap do not throw. If they do, basic standard-library invariants are broken.
标准库假设析构函数,内存释放函数(例如delete运算符),swap都不会抛出异常。如果它们异常,标准库的不变量就被破坏了。
Note(注意)
Deallocation functions, including operator delete, must be noexcept. swap functions must be noexcept. Most destructors are implicitly noexcept by default. Also, make move operations noexcept.
包含delete运算符的内存释放函数一定不要抛出异常。swap函数一定不要抛出异常。大多数析构函数默认情况下
Enforcement(实施建议)
Catch destructors, deallocation operations, and swaps that throw. Catch such operations that are not noexcept.
捕捉抛出异常的析构函数,内存释放操作和swap函数。捕捉这些操作中没有声明为noexcept的情况。
See also: discussion
参见:问题讨论
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e16-destructors-deallocation-and-swap-must-never-fail
新书介绍
以下是本人3月份出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!