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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With