How do I use noexcept and when to mark functions noexcept?

In C++, the `noexcept` specifier is used to indicate whether a function is allowed to throw exceptions. By marking a function as `noexcept`, you are communicating to the compiler and other developers that this function will not throw any exceptions. If an exception does occur within a `noexcept` function, the program will call `std::terminate`, leading to abnormal program termination.

When to mark functions as `noexcept`:

  • When you are certain that the function does not throw any exceptions, such as in simple accessor functions or in functions that handle exceptions internally.
  • In performance-critical code, where exception handling may introduce unnecessary overhead.
  • When implementing move constructors and move assignment operators, as these should not throw exceptions to ensure strong exception safety guarantees.

Here is an example of using `noexcept` in a function:

void functionNoExcept() noexcept {
            // Function logic that does not throw exceptions
        }

        void functionWithException() { 
            throw std::runtime_error("This will throw");
        }
        
        

noexcept C++ exception safety performance move semantics