Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

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.

like image 525
LB-- Avatar asked Apr 26 '13 20:04

LB--


People also ask

What does Noexcept false do?

In contrast, noexcept(false) means that the function may throw an exception. The noexcept specification is part of the function type but can not be used for function overloading. There are two good reasons for the use of noexcept: First, an exception specifier documents the behaviour of the function.

Should I add Noexcept?

Templates like move_if_noexcept will detect if the move constructor is defined with noexcept and will return a const& instead of a && of the type if it is not. It's a way of saying to move if it is very safe to do so. In general, you should use noexcept when you think it will actually be useful to do so.

Does Noexcept make code faster?

That noexcept keyword is tricky, but just know that if you use it, your coding world will spin faster.

What's the point of Noexcept?

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.


1 Answers

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.

like image 93
GManNickG Avatar answered Nov 08 '22 12:11

GManNickG