Stephen Meyer's Book
Item 14. Declare functions noexcept if they won't emit exceptions
-
The main incentive is optimization (no need to hold runtime stack state).
Whenever an exception is thrown, the runtime must wind back the stack to the state where it was before the function being called. -
Strong exception safety guarantee. It is the guarantee that, whenever an exception occurs and an operation is not complete, the previous state is restored and the program is not corrupted It is the guarantee that, whenever an exception occurs and an operation is not complete, the previous state is restored and the program is not corrupted.
-
C++11 can improve code performance of legacy code due to move semantincs. Think about a vector that reaches its limit and a
push_backis called. In C++11, instead of copying everything, it now moves everything. But you should implement the move constructor in the type you are moving or at least guarantee that the conditions for automatic generation are fullfilled. -
But replacing copy by move affests the SESG of
push_back. Therefore, C++11 should only use the optimized move operation whenever it is guaranteed that the move operation won't throw any exception. -
A
Therefore, the swap of pairs isswapimplementation for pairs looks something like:noexceptonly if the swap between its lower level structures isnoexcept. Theswapoperation is used very often in STL implementation, so in order to take advantage of the optimization described above, it is a good idea to declare your defined swaps noexcept (it can be automatically generated?) -
The
noexceptkeyword: noexcept; noexcept(false); noexcept(boolean condition). -
noexceptis part of the function interface in the same way the keywordconstis also part of the function interface. -
Most functions are exception-neutral. That is, they don't throw exceptions themselves but they call functions that do.