![952944624417f5b78511b0131f5a1a16.png](https://i-blog.csdnimg.cn/blog_migrate/46b1800453b77324c565c9e2ecfa5279.jpeg)
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
觉得本文有帮助?请分享给更多人。
更多文章请关注微信公众号【面向对象思考】!
面向对象开发,面向对象思考!