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

2020-08-04 17:08:37 浏览数 (1)

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

0 人点赞