4

I'm trying to understand noexcept. I came to know global swap function is generally specified like this

void swap (T& x, T& y) noexcept(noexcept(x.swap(y)))
{
   x.swap(y);
}

I want to understand why noexcept specification is noexcept(noexcept(x.swap(y))) but not noexcept(x.swap(y)).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Infinity
  • 165
  • 1
  • 1
  • 7

1 Answers1

6

These are two kinds of usage of noexcept.

The noexcept operator used in noexcept(x.swap(y)) would return true if x.swap(y) is declared not to throw, and false otherwise.

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.

The noexcept specifier is used to specify whether a function could throw exceptions. noexcept(noexcept(x.swap(y))) specifies swap throws or not according to the result of noexcept(x.swap(y)); i.e. whether swap could throw or not depends on whether x.swap(y) could throw or not.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    Thanks a lot. I wasn't aware noexcept keyword had two roles, one as a specifier and one as an operator. Now its clear! – Infinity Dec 22 '21 at 04:22
  • @Infinity In C++20 [we'll have](https://stackoverflow.com/questions/54200988/why-do-we-require-requires-requires) something similar for `requires`. – Evg Dec 22 '21 at 08:27