12

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?

j__
  • 632
  • 4
  • 18
  • Related: https://stackoverflow.com/questions/63727975/when-should-one-explicitly-attribute-noexcept – j__ Sep 03 '20 at 16:31

1 Answers1

14

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.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • Why would one prefer to copy if both can throw? – j__ Sep 03 '20 at 16:06
  • 4
    @lajoh90686 If you start moving elements and one throws it isn't possible to undo the changes. You have two arrays each containing a portion of the elements and you can't be sure moving them back will work (because evidently moving can fail). If you start copying elements and one throws you can just throw away the new partially copied array and the old data is preserved. – François Andrieux Sep 03 '20 at 16:07
  • 2
    @lajoh90686 pretty much anytime you want to ensure the strong exception guarantee – Caleth Sep 03 '20 at 16:13