I have read unclear things regarding the noexcept specifier and compiler optimizations. When specifying noexcept
the compiler may optimize:
Declaring a function noexcept helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure. The keyword noexcept serves two purposes (like most of the language, really): It's an instruction to the compiler, and it's also helpful to humans who are reading the code.
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.
The dynamic exception specification, or throw(optional_type_list) specification, was deprecated in C++11 and removed in C++17, except for throw() , which is an alias for noexcept(true) . We recommended you apply noexcept to any function that never allows an exception to propagate up the call stack.
Note that noexcept doesn't actually prevent the function from throwing exceptions or calling other functions that are potentially throwing. Rather, when an exception is thrown, if an exception exits a noexcept function, std::terminate will be called.
The original reason for noexpect was to enable libraries to use faster move-constructors internally, if the calling function is not allowed to throw by specification.
Next, big performance optimizations can be achieved in containers like STL vector when your type’s move constructor and move assignment are annotated with noexcept. When STL utility std::move_if_noexcept detects that your moves do not throw it will use these safe moves rather than copies for some operations (like resize). This, in case of containers storing millions of elements, will enable huge optimizations.
(quoted from using-noexcept)
Additionally, the compiler does not have to generate extra code for stack-unwinding, if it knows that no exceptions can be thrown due to a noexpect specifier.
I can't see how compile-time is substantially impacted by noexcept-specifiers. The resulting runtime can be a lot faster though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With