Skip to content

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_back is 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 swap implementation for pairs looks something like:

    void swap(pair& p) noexcept(noexcept(swap(first, p.first)) && noexcept(swap(second, p.second)))
    
    Therefore, the swap of pairs is noexcept only if the swap between its lower level structures is noexcept. The swap operation 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 noexcept keyword: noexcept; noexcept(false); noexcept(boolean condition).

  • noexcept is part of the function interface in the same way the keyword const is 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.