Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between noexcept and empty throw specification for an lambda expression?

Given an example:

double values[] {2.5, -3.5, 4.5, -5.5, 6.5, -7.5};
std::vector<double> squares(std::end(values) - std::begin(values));

std::transform(std::begin(values), std::end(values), std::begin(values), std::begin(squares),
    [](double x1, double x2) throw() { return x1 * x2; });
  1. Is this functionally equivalent to the following?

    [](double x1, double x2) noexcept { return x1 * x2; })
    
  2. Is there a convincible reason, why should I mark such expression (or similar basic expresions) with either modifiers or in this case, it is better to leave it and simply don't bother?

like image 735
Grzegorz Szpetkowski Avatar asked May 25 '16 09:05

Grzegorz Szpetkowski


2 Answers

Is there any difference between noexcept and empty throw specification...?

Yes there is.

The first difference that comes to mind is what happens if an exception is thrown?

  • In the case of throw(), std::unexpected() is called. The default handler for unexpected will call terminate.
  • In the case of noexcept, std::terminate() is called.

The second is that the dynamic exception specification is deprecated.

Deprecates

noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().


Is there a convincible reason, why should I mark such expression (or similar basic expresions) with either modifiers...?

It is an expression of intent. If you intend that the lambda never throws, and if it does it is deemed fatal to the execution of the program, then yes - you should mark the lambda as noexcept (throw() is deprecated).

like image 149
Niall Avatar answered Sep 22 '22 17:09

Niall


Yes, they both could be used for declaring functions (including lambdas) which don't throw any exceptions, but dynamic exception specification has been deprecated in C++11. And noexcept (same as noexcept(true)) and throw() are not exactly the same:

noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().

like image 45
songyuanyao Avatar answered Sep 22 '22 17:09

songyuanyao