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的;只要有一个(析构时,译者注)抛出异常的成员,就会破坏整个继承体系。
左右滑动查看更多
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 declarednoexcept
if it could throw.
(简单)如果存在抛出异常的风险,则将析构函数定义为noexcept。
原为链接
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】