c++ - 递归 noexcept() 是什么意思?

标签 c++ noexcept

标准库定义了数组和 std::pair 的交换,如下所示:

template <class T, size_t N>
void swap(T (&a)[N],
          T (&b)[N]) noexcept(noexcept(swap(*a, *b)));

template <class T1, class T2>
struct pair {
    …
    void swap(pair& p) noexcept(noexcept(swap(first,  p.first)) &&
                                noexcept(swap(second, p.second)));
    …
};

Effective Modern C++ Item 14 说:

[…] whether they are noexcept depends on whether the expression inside the noexcept clauses are noexcept.
Given two arrays of Widget, for example, swapping them is noexcept only if swapping individual elements in the arrays is noexcept, i.e. if swap for Widget is noexcept.
That, in turn, determines whether other swaps, such as the one for arrays of arrays of Widget, are noexcept.
Similarly, whether swapping two std::pair objects containing Widgets is noexcept depends on whether swap for Widgets is noexcept.

但是从这个解释中,我无法理解为什么有必要将调用嵌套为 noexcept(noexcept(swap(*a, *b)))

如果目标是“交换两个数组应该像交换元素一样 noexcept”,为什么 noexcept(swap(*a, *b)) 还不够?

这些是 noexcept() 的不同重载还是什么?

最佳答案

这不是“递归”noexceptnoexcept 关键字有两种用法:

  • noexcept specifier - 将函数标记为 noexcept 并可选择将 bool 常量表达式作为参数

  • noexcept operator - 它以一个表达式作为参数并返回一个 bool 常量表达式,表示该表达式是否为noexcept


在你的情况下:

//          `noexcept` operator
//          v~~~~~~~~~~~~~~~~~~~~~
   noexcept(noexcept(swap(*a, *b)))
// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// `noexcept` specifier

关于c++ - 递归 noexcept() 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508395/

相关文章:

c++ - 使用 noexcept 作为 lambda 修饰符或参数约束

c++ - g++-4.8.1 认为显式声明的没有异常规范的析构函数总是 noexcept(true)

c++ - 使用 60K+ 条目初始化类静态映射

c++ - 水平对齐动态创建的小部件 qt c++

c++ - 未定义的函数引用(链接器错误)

c++ - i2c 字节写函数,这段代码是如何工作的?我完全不能理解

c++ - Vector 没有退缩

c++ - 为什么 ValueType 的 std::any & operator= 不是有条件的 noexcept?

c++ - std::terminate 和空容器的析构函数

c++ - 从C++函数中删除noexcept,如何处理调用它的noexcept函数?