Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is noexcept useless when not throwing is zero-cost?

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?

like image 547
j__ Avatar asked Sep 03 '20 15:09

j__


People also ask

Why do we need Noexcept?

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.

Should constructors be Noexcept?

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.

When should I use Noexcept keyword?

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.

Is Noexcept faster?

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.


1 Answers

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.

like image 89
François Andrieux Avatar answered Sep 24 '22 14:09

François Andrieux