Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ISO noexcept of noexcept

Tags:

c++

noexcept

In the C++ standard there is the following definition:

template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])       noexcept(noexcept(swap(*a, *b))); 

What does noexcept(noexcept(swap(*a, *b))) do?

like image 515
yonutix Avatar asked Feb 09 '18 10:02

yonutix


People also ask

What does Noexcept mean?

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.

Is Noexcept required?

Explicit instantiations may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations.

What is Const Noexcept C++?

noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never. noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception.

Why do we use Noexcept?

There are two good reasons for the use of noexcept: First, an exception specifier documents the behaviour of the function. If a function is specified as noexcept, it can be safely used in a non-throwing function. Second, it is an optimisation opportunity for the compiler.


1 Answers

Having the noexcept(x) specifier in a function declaration means that the function is non-throwing if and only if x evaluates to true.

noexcept(y) can also be used as an operator, evaluating to true if y is a non-throwing expression, and to false if y can potentially throw.

Combined, this means void foo() noexcept(noexcept(y)); means: foo is non-throwing exactly when y is non-throwing.

In the case in the question, the function template swap for arrays is declared to be non-throwing if and only if swapping individual members of the arrays is non-throwing, which makes sense.

like image 131
Angew is no longer proud of SO Avatar answered Oct 02 '22 09:10

Angew is no longer proud of SO