Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disabled exceptions and noexcept()

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?

like image 249
onqtam Avatar asked May 16 '15 14:05

onqtam


People also ask

What does Noexcept mean in C++?

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.

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 happens when Noexcept function throws?

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.

What does it mean to specify a function as Noexcept false?

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.


1 Answers

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.

like image 65
Columbo Avatar answered Sep 20 '22 05:09

Columbo