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

952944624417f5b78511b0131f5a1a16.png

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的;只要有一个(析构时,译者注)抛出异常的成员,就会破坏整个继承体系。

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


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

更多文章请关注微信公众号【面向对象思考】!

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值