Article 14 of "Effective Modern C++" study notes: As long as the function does not emit an exception, add a noexcept statement to it

First of all, if you know that a function cannot throw an exception, you should declare it as noexcept to improve the efficiency of the code. However, if the function illegally declares that it throws an exception, the program will be aborted directly.

In both C++98 and C++11, you can declare that a function will not throw an exception. The code is as follows:

int f(int x) throw(); //f不会抛出异常,C++98风格

int f(int x) noexcept; //f不会抛出异常,C++11风格

There are several reasons for the benefits of using noexcept instead of throw():

  1. Declared as nocept, the optimizer will optimize the function to the maximum value, including keeping the executor stack in an unsolvable state.
  2. C++11 has added move semantics, so the STL standard library has also made a major performance adjustment, that is, in the original assignment operation, the strategy of "move if possible, copy only" will be adopted. A key point of whether the mobile can be moved is whether the STL function declares noexcept. Whether the STL function declares noexcept depends on whether the function corresponding to the custom object contained in the STL container declares noexcept. For example: if the move copy function of a custom object declares noexcept, then when the object is expanded after push_back, move copy will be used instead of copy copy, or noexcept is declared for the swap() member function of an object, then The container will use mobile copy when calling the swap() function of STL.
  3. By default, all memory release functions (delete functions) or destructors, whether user-defined or generated by the compiler, implicitly declare noexcept.

Shorthand

  • The noexcept statement is part of the functional interface, which means that the caller may depend on it
  • Compared with functions without nocept declarations, functions with nocept declarations have more opportunities to be optimized
  • The noexcept nature is the most valuable for mobile operations, swap, memory release functions, and destructors
  • Most functions are exceptionally neutral and do not have the nature of noexcept

 

Guess you like

Origin blog.csdn.net/Chiang2018/article/details/114241449