std::swap
is declared this way:
template <class T> void swap (T& a, T& b)
noexcept (is_nothrow_move_constructible<T>::value &&
is_nothrow_move_assignable<T>::value);
If I disable exceptions in my program (like with -fno-exceptions
for g++) will std::swap
use move operations for my custom types if they are move-enabled no matter if they are noexcept or not?
EDIT: follow-up question:
After realizing that std::swap will always use moves if my type has them, my real question is what happens to traits like is_nothrow_move_assignable<>
?
Will std::vector
always use moves when reallocating if my types have noexcept(true)
move operations?
A noexcept-expression is a kind of exception specification: a suffix to a function declaration that represents a set of types that might be matched by an exception handler for any exception that exits a function.
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.
Note that noexcept doesn't actually prevent the function from throwing exceptions or calling other functions that are potentially throwing. Rather, when an exception is thrown, if an exception exits a noexcept function, std::terminate will be called.
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.
The noexcept-specification on swap
solely tells the user where she can use swap
without encountering an exception. The implementation is practically always equivalent to
auto tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
Which moves the objects around if, and only if, overload resolution selects a move assignment operator and/or constructor.
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