C++中怎么保证析构函数不抛出异常-成都快上网建站

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

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

创新互联基于成都重庆香港及美国等地区分布式IDC机房数据中心构建的电信大带宽,联通大带宽,移动大带宽,多线BGP大带宽租用,是为众多客户提供专业服务器托管报价,主机托管价格性价比高,为金融证券行业服务器主机托管,ai人工智能服务器托管提供bgp线路100M独享,G口带宽及机柜租用的专业成都idc公司。

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++中怎么保证析构函数不抛出异常的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


分享题目:C++中怎么保证析构函数不抛出异常
标题路径:http://kswjz.com/article/ihoeod.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流