I saw that C++ 11 added the noexcept
keyword. But I don't really understand why is it useful.
If the function throws when it's not supposed to throw - why would I want the program to crash?
So when should I use it?
Also, how will it work along with compiling with /Eha and using _set_se_translator
? This means that any line of code can throw c++ exception - because it might throw a SEH exception (Because of accessing protected memory) and it will be translated to c++ exception.
What will happen then?
The primary use of
noexcept
is for generic algorithms, e.g., when resizing astd::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 thenoexcept(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 usenoexcept
,throw()
, ornoexcept(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:Based on
noexcept(swap(a, b))
the library can then choose differently efficient implementations of certain operations: if it can justswap()
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.: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)
).T::T(T&&)
) and move assignment (T::operator=(T&&)
).swap()
operations (swap(T&, T&)
and possibly the member versionT::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 beingnoexcept
they can be declared (and possible changed as necessary) in the future.