noexcept specifier is used to mark a function as non-throwing. A non-throwing function is a function that does not throw any exception or calls any other function that throws.
A function can be marked as non-throwing using noexcept as shown below:
void doSomething() noexcept
{
//
}doSomething is marked as noexcept which makes it a non-throwing function. However, it does not mean that the function can’t throw any exception. But it is like a promise that the function is giving to its caller that it would not throw any exception.
If a function marked as noexcept and it throws an exception, the program ends then and there with std::terminate.
There might be places where a non-throwing function is required to be used. For example, it is a must to use non-throwing functions in destructors because destructors should not throw any exception because to let stack unwinding operation finish successfully if any other exception comes (explained in this note).
There are following functions which are always non-throwing and should be marked as noexcept:
- Move constructors and assignment operator (see the example in this note)
- Swap functions
noexcept operator
noexcept can also be used as operator which statically determines if a function or an expression is non-throwing. It happens at compilation time so it does not evaluate the expression or calls the function.
For example:
void no_thrower() noexcept
{
}
void may_throw()
{
}
int main(int argc, char const *argv[])
{
std::cout << noexcept(no_thrower()) << '\n'; // shows 1 (true)
std::cout << noexcept(may_throw()) << '\n'; // shows 0 (false)
return 0;
}