j__
j__

Reputation: 740

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?

Upvotes: 12

Views: 367

Answers (1)

François Andrieux
François Andrieux

Reputation: 29022

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.

Upvotes: 14

Related Questions