Does adding `noexcept(false)` benefit the code in any way?

后端 未结 2 1115
执笔经年
执笔经年 2021-02-12 11:12

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 w

2条回答
  •  孤独总比滥情好
    2021-02-12 11:51

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

    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.


    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.

    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).

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

提交回复
热议问题