温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么保证析构函数不抛出异常

发布时间:2021-07-28 11:43:03 来源:亿速云 阅读:246 作者:Leah 栏目:大数据

C++中怎么保证析构函数不抛出异常,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

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(注意)
C++中怎么保证析构函数不抛出异常    

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(示例)
C++中怎么保证析构函数不抛出异常    

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(注意)
C++中怎么保证析构函数不抛出异常    

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

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

Enforcement(实施建议)
C++中怎么保证析构函数不抛出异常    

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

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


看完上述内容,你们掌握C++中怎么保证析构函数不抛出异常的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI