18

If I mark a function as noexcept(false), or any other expression which evaluates to false, what does it means? (1) am I ensuring to the compiler that the function can throw an exception?, (2) or am I ensuring nothing about whether it can throw exceptions or not?

And lastly, if I omit the noexcept specifier, it is equivalent to noexcept(false), or only equivalent to the (2)nd meaning stated above?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ABu
  • 10,423
  • 6
  • 52
  • 103
  • If you take `noexcept(false)` to be the opposite of `noexcept(true)`, [a reference](http://en.cppreference.com/w/cpp/language/noexcept_spec) answers everything. – chris Apr 21 '15 at 15:26

2 Answers2

17

By specifying noexcept(true), you claim that the function never throws exceptions. By specifying noexcept(false), or not specifying anything, you do not claim that the function never throws exceptions.

So it's basically your statement (2), but note that for the compiler, that's equivalent to your statement (1). If the compiler is not assured that the function will not throw, it must assume that it can.

The relevant bit of the standard is C++11 15.4/12:

A function with no exception-specification or with an exception-specification of the form noexcept(constant-expression) where the constant-expression yields false allows all exceptions. An exception-specification is non-throwing if it is of the form throw(), noexcept, or noexcept(constant-expression) where the constant-expression yields true. A function with a non-throwing exception-specification does not allow any exceptions.

There are only two deviations from that rule. One is destructors—putting no exception specification on a destructor gives the destructor the same exception specification as the default-generated one would have. That is, noexcept(true) if and only if all functions which would be directly invoked from the default-generated destructor are noexcept(true).

The other one are deallocation functions (operator delete)—a deallocation function without an explicit exception specification is treated as noexcept(true).

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • 1
    @Deduplicator Changed the wording regarding the functions, but I can't seem to find a reference to constructors behaving the same. Can you provide a paragraph number? – Angew is no longer proud of SO Apr 21 '15 at 15:34
  • 1
    @Deduplicator Only if it's not user-provided (i.e., implicitly declared or explicitly defaulted on first declaration). See [dcl.fct.def.default]/p2, [except.spec]/14. – T.C. Apr 21 '15 at 15:39
  • You also missed deallocation functions, which are by default `noexcept(true)`. – T.C. Apr 21 '15 at 15:41
9

Omitting the noexcept specifier is equivalent to noexcept(false), except for destructors, where omitting the specifier means letting the compiler deduce from the members and base classes.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157