前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.37:保证析构函数不会抛出异常

C++核心准则C.37:保证析构函数不会抛出异常

作者头像
面向对象思考
发布2020-03-25 16:06:59
7320
发布2020-03-25 16:06:59
举报
文章被收录于专栏:C++核心准则原文翻译

C.37: Make destructors noexcept

C.37:保证析构函数不会抛出异常

Reason(原因)

A destructor may not fail. If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.

所有的析构函数都可以不失败。如果析构函数试图抛出异常退出,这是严重的设计错误,更好的选择是中止程序。

Note(注意)

A destructor (either user-defined or compiler-generated) is implicitly declared noexcept (independently of what code is in its body) if all of the members of its class have noexcept destructors. By explicitly marking destructors noexcept, an author guards against the destructor becoming implicitly noexcept(false) through the addition or modification of a class member.

如果类的所有的成员的析构函数都是noexcept的,它的析构函数(无论是用户定义的还是编译器生成的)就会被隐式定义为noexcept(这和函数体内的具体代码无关)。通过显式定义析构函数为noexcept,可以防止析构函数由于类成员被修改而无法成为noexcpet。

Example(示例)

Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy

不是所有的析构函数都默认是noexcept的;只要有一个(析构时,译者注)抛出异常的成员,就会破坏整个继承体系。

代码语言:javascript
复制
struct X {
    Details x;  // happens to have a throwing destructor
    // ...
    ~X() { }    // implicitly noexcept(false); aka can throw 
};

左右滑动查看更多

So, if in doubt, declare a destructor noexcept.

因此,如果有疑问,就将析构函数定义为noexcept。

Note(注意)

Why not then declare all destructors noexcept? Because that would in many cases -- especially simple cases -- be distracting clutter.

为什么不将所有的析构函数都定义为noexcept?因为在很多场合,特别是简单的场合这样做只会增加干扰信息。

Enforcement(实施建议)

(Simple) A destructor should be declarednoexceptif it could throw.

(简单)如果存在抛出异常的风险,则将析构函数定义为noexcept。

原为链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c37-make-destructors-noexcept


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • A destructor may not fail. If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档