6

In a generic context, it is quite often we write something like

return_type f(arg_type1 arg1, ...)
  noexcept(noexcept(statement_1) && noexcept(statement_2) && ... && noexcept(statement_n))
{
  statement_1;
  statement_2;
  ...
  statement_n;
}

When a statement_k is a return statement, things aren't so simple. It is just impossible to write noexcept(return expr). Instead, I should understand what's going on when we say return expr and break down it into several noexcept(something)'s. But it seems quite nontrivial.

I've come up with something like the following algorithm:

  1. If return_type is a reference type, then of course noexcept(expr) suffices.
  2. If return_type is not a reference type but if return expr is a situation where guaranteed copy elision happens then again noexcept(expr) suffices.
  3. Otherwise, noexcept(expr) && std::is_nothrow_move_constructible<return_type>::value && std::is_nothrow_destructible<return_type>::value.

Is it right? Or is there any simpler way? The case 1 would be subsumed as a special case of case 3, but how about case 2 and 3?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Junekey Jeon
  • 1,496
  • 1
  • 11
  • 18
  • You want a `noexcept(auto)` as we have for `decltype`. – Jarod42 Jul 13 '18 at 12:32
  • 2
    Related to: [is-there-an-automatic-noexcept-specifier](https://stackoverflow.com/questions/30456801/is-there-an-automatic-noexcept-specifier) – Jarod42 Jul 13 '18 at 12:33
  • @Jarod42 AFAIK, the author of that proposal withdrew it.... Too bad – Junekey Jeon Jul 13 '18 at 12:35
  • 3
    @JunekeyJeon: There is no function that needs to be correctly `noexcept` *that badly*. It's much better to just not care in such cases. You're setting yourself up for a maintenance nightmare for something that, ultimately, just doesn't matter that much. – Nicol Bolas Jul 13 '18 at 13:46
  • 1
    Case 3 is incorrect if `decltype(expr)` is not the same as `return_type`, ie there is a type conversion occurring in the expression – Eric Sep 25 '19 at 05:48
  • @Eric Thanks for pointing it out. How about something like ````noexcept(return_type{ expr })````? – Junekey Jeon Sep 26 '19 at 04:48

0 Answers0