Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ standard library implementations allowed to strengthen noexcept specifications?

According to the C++ standard, are implementations of the C++ standard library allowed to strengthen noexcept specifications of methods and other functions of the C++ standard library as defined by the standard?

For example, if the C++ standard specifies some function std::f as void f(); are standard library implementations allowed to implement it as void f() noexcept; instead?

like image 577
jotik Avatar asked Jun 27 '16 10:06

jotik


People also ask

Can be declared Noexcept?

"Function can be declared 'noexcept'." If code is not supposed to cause any exceptions, it should be marked as such by using the 'noexcept' specifier. This would help to simplify error handling on the client code side, as well as enable compiler to do additional optimizations.

What is Noexcept CPP?

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.


1 Answers

The Standard says yes:

§ 17.6.5.12.1 Restrictions on exception handling [res.on.exception.handling]

  1. Any of the functions defined in the C++ standard library can report a failure by throwing an exception of a type described in its Throws: paragraph. An implementation may strengthen the exception specification for a non-virtual function by adding a non-throwing noexcept-specification.

[...]

  1. Destructor operations defined in the C++ standard library shall not throw exceptions. Every destructor in the C++ standard library shall behave as if it had a non-throwing exception specification. Any other functions defined in the C++ standard library that do not have an exception-specification may throw implementation-defined exceptions unless otherwise specified. An implementation may strengthen this implicit exception-specification by adding an explicit one.

(Comma 4 seems to just allow to be explicit about the exception specification, and to warn that the lack of an explicit exception specification means that the implementation is allowed to throw anything).


To be honest, I don't understand why this is allowed and adding constexpr is not (§ 17.6.5.6). They look like the two sides of the same medal -- by using type traits and SFINAE you can have code which shows different behaviours depending on which Standard Library implementation you use (if it marks some functions as noexcept/constexpr, or if it doesn't), and that defeats the purposes of having a standard in the first place...

like image 171
peppe Avatar answered Sep 20 '22 13:09

peppe