Using the noexcept specifier

The noexcept specifier is used to tell the compiler whether a function may or may not throw a C++ exception. If a function is marked with the noexcept specifier, it is not allowed to throw an exception and, if it does, std::terminate() will be called when the exception is thrown. If the function doesn't have the noexcept specifier, exceptions can be thrown as normal.

In this recipe, we will explore how to use the noexcept specifier in your own code. This specifier is important because it is a contract between the API that you are creating and the user of the API. When the noexcept specifier is used, it tells the user of the API that they do not need to consider exceptions when using the API. It also tells the author that if they add the noexcept specifier to their API, they have to ensure that no exceptions are thrown, which, in some cases, requires the author to catch all possible exceptions and either handle them or call std::terminate() if the exception cannot be handled. Also, there are certain operations, such as std::move, where exceptions cannot be thrown without the fear of corruption as a move operation oftentimes cannot be safely reversed if an exception is thrown. Finally, with some compilers, adding noexcept to your APIs will reduce the overall size of the function, resulting in a smaller overall application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset