前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.12: 当不可能或不愿意通过抛出异常退出函数时使用noexcept

C++核心准则E.12: 当不可能或不愿意通过抛出异常退出函数时使用noexcept

作者头像
面向对象思考
发布2020-08-04 17:08:37
5680
发布2020-08-04 17:08:37
举报

E.12: Use noexcept when exiting a function because of a throw is impossible or unacceptable

E.12: 当不可能或不愿意通过抛出异常退出函数时使用noexcept

Reason(原因)

To make error handling systematic, robust, and efficient.

为了让错误处理更系统化,健壮和高效。

Example(示例)

代码语言:javascript
复制
double compute(double d) noexcept
{
    return log(sqrt(d <= 0 ? 1 : d));
}

Here, we know that compute will not throw because it is composed out of operations that don't throw. By declaring compute to be noexcept, we give the compiler and human readers information that can make it easier for them to understand and manipulate compute.

因为这段代码有不会抛出异常的操作构成,所以我们知道compute函数不会抛出异常。通过将compute函数定义为noexcept,我向编译器和代码的读者传递了可以让它们更容易理解和维护代码的信息。

Note(注意)

Many standard-library functions are noexcept including all the standard-library functions "inherited" from the C Standard Library.

很多标准库函数被定义为noexcept,包含所有从C标准库继承的标准库函数。

Example(示例)

代码语言:javascript
复制
vector<double> munge(const vector<double>& v) noexcept
{
    vector<double> v2(v.size());
    // ... do something ...
}

The noexcept here states that I am not willing or able to handle the situation where I cannot construct the local vector. That is, I consider memory exhaustion a serious design error (on par with hardware failures) so that I'm willing to crash the program if it happens.

这里的noexcept说明我不愿意或者不能处理局部的vecrot构建失败的情况。也就是说,我认为内存耗尽是严重的设计错误(和硬件错误同样看待),如果这种情况发生,我甘愿终止程序。

Note(注意)

Do not use traditional exception-specifications.

不要使用传统的例外定义方式。

See also(参见)

discussion.

课题讨论。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e12-use-noexcept-when-exiting-a-function-because-of-a-throw-is-impossible-or-unacceptable

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档