前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.16:析构函数,内存释放和swap操作永远不能失败

C++核心准则E.16:析构函数,内存释放和swap操作永远不能失败

作者头像
面向对象思考
发布2020-08-04 17:09:45
7050
发布2020-08-04 17:09:45
举报

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(反面示例)

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档