添加`noexcept(false)`是否以任何方式使代码受益? [英] Does adding `noexcept(false)` benefit the code in any way?

查看:225
本文介绍了添加`noexcept(false)`是否以任何方式使代码受益?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近在我的代码中,我已经在我知道确实会引发异常的函数上显式编写noexcept(false),主要是供那些阅读代码的人使用.但是,我想知道这是否影响我的代码的行为或编译器解释它的方式.有什么区别吗?

Recently in my code I have been explicitly writing noexcept(false) on functions that I know do throw exceptions, mainly for people reading the code. However, I am wondering if this affects the behavior of my code or the way the compiler interprets it. Does it make any difference?

注意:我知道析构函数是隐式的noexcept,并且您必须指定noexcept(false)来进行更改,我想知道其他函数.

Note: I am aware that destructors are implicitly noexcept and that you have to specify noexcept(false) to change that, I am wondering about other functions.

推荐答案

没有异常说明符,并且明确声明noexcept(false)是等效的,请参见§15.4/12:

Having no exception-specifier and explicitly stating noexcept(false) are equivalent, see §15.4/12:

没有异常规范或形式为noexcept(constant-expression)的异常规范的函数,其中常量表达式产生false允许所有异常.

A function with no exception-specification or with an exception-specification of the form noexcept(constant-expression) where the constant-expression yields false allows all exceptions.

因此,在考虑异常时,编译器不应区分它们.

So the compiler should not distinguish between them when considering exceptions.

更重要的是,您无需将noexcept(false)附加到函数上.作为C ++开发人员,您应该假设默认情况下每个函数都会抛出异常(这就是标准采取这种立场的原因),因此您无需通过写入来添加任何新信息.这对每个人都是浪费时间.

More importantly, there's no need for you to be tacking on noexcept(false) to your functions. As a C++ developer, you should assume every function throws by default (which is why the standard takes this stance), so you're adding no new information by writing it out; it's a waste of time for everyone.

相反,请确实标记一个函数绝对不会与noexcept一起抛出的特殊情况,并标记一个函数可能根据某些条件而抛出的情况与noexcept(condition).

Rather, do mark the special case where a function definitely does not throw with noexcept, and do mark the cases where a function may throw depending on some condition with noexcept(condition).

如果您的功能是有目的的某些异常E的来源,请将其写在文档中.

If your function is purposefully the source of some exception E, write that in your documentation.

这篇关于添加`noexcept(false)`是否以任何方式使代码受益?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆