首页 文章详情

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

面向对象思考 | 320 2020-07-31 15:20 0 0 0
UniSMS (合一短信)

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(示例)

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(示例)

vector munge(const vector& v) noexcept
{
vector 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

新书介绍

以下是本人3月份出版的新书,拜托多多关注!


本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter