Is the noexcept
specifier useless if your implementation has a zero-cost (if nothing is thrown) exception model? What is an example where lacking noexcept
has a consequence?
There are two good reasons for the use of noexcept: First, an exception specifier documents the behaviour of the function. If a function is specified as noexcept, it can be safely used in a non-throwing function. Second, it is an optimisation opportunity for the compiler.
In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.
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.
Looking at those results, the tests where noexcept-move was possible saw a speedup of ~1.3 relative to their non-noexcept-movable counterparts in both benchmarks.
Is the
noexcept
specifier useless if your implementation has a zero-cost (if nothing is thrown) exception model?
No, noexcept
would be useful even if exceptions had no performance impact at all.
One example is that noexcept
can signal which algorithm can be used. For example algorithms that use std::move_if_noexcept
or many of the standard type_traits could behave differently depending on the presence of noexcept
.
This can have a significant impact for common features like std::vector
which will be much slower if you elements' move constructor isn't noexcept
. std::vector
will copy all elements when reallocating instead of moving them if the move constructor is not noexcept
to preserve the strong exception guarantee.
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