The primary use of noexcept
is for generic algorithms, e.g., when resizing a std::vector<T>
: for an efficient algorithm moving elements it is necessary to know ahead of time that none of the moves will throw. If moving elements might throw, elements need to be copied instead. Using the noexcept(expr)
operator the library implementation can determine whether a particular operation may throw. The property of operations not throwing becomes part of the contract: if that contract is violated, all bets are off and there may be no way to recover a valid state. Bailing out before causing more damage is the natural choice.
To propagate knowledge about noexcept
operations do not throw it is also necessary to declare functions as such. To this end, you'd use noexcept
, throw()
, or noexcept(expr)
with a constant expression. The form using an expression is necessary when implementing a generic data structure: with the expression it can be determined whether any of the type dependent operations may throw an exception.
For example, std::swap()
is declared something like this:
template <typename T>
void swap(T& o1, T& o2) noexcept(noexcept(T(std::move(o1)) &&
noexcept(o1 = std::move(o2)));
Based on noexcept(swap(a, b))
the library can then choose differently efficient implementations of certain operations: if it can just swap()
without risking an exception it may temporarily violate invariants and recover them later. If an exception might be thrown the library may instead need to copy objects rather than moving them around.
It is unlikely that the standard C++ library implementation will depend on many operations to be noexcept(true)
. The probably the operations it will check are mainly those involved in moving objects around, i.e.:
- The destructor of a class (note that destructors are by default
noexcept(true)
even without any declaration; if you have destructor which may throw, you need to declare it as such, e.g.: T::~T() noexcept(false)
).
- The move operators, i.e. move construction (
T::T(T&&)
) and move assignment (T::operator=(T&&)
).
- The type's
swap()
operations (swap(T&, T&)
and possibly the member version T::swap(T&)
).
If any of these operations deviates from the default you should declare it correspondingly to get the most efficient implementation. The generated versions of these operations declare whether they are throwing exceptions based on the respective operations used for members and bases.
Although I can imagine that some operations may be added in the future or by some specific libraries, I would probably not declaration operations as noexcept
for now. If other functions emerge which make a difference being noexcept
they can be declared (and possible changed as necessary) in the future.