标准库定义了数组和 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 thenoexcept
clauses arenoexcept
.
Given two arrays ofWidget
, for example, swapping them isnoexcept
only if swapping individual elements in the arrays isnoexcept
, i.e. if swap forWidget
isnoexcept
.
That, in turn, determines whether other swaps, such as the one for arrays of arrays ofWidget
, arenoexcept
.
Similarly, whether swapping twostd::pair
objects containingWidget
s isnoexcept
depends on whether swap forWidget
s isnoexcept
.
但是从这个解释中,我无法理解为什么有必要将调用嵌套为 noexcept(noexcept(swap(*a, *b)))
。
如果目标是“交换两个数组应该像交换元素一样 noexcept
”,为什么 noexcept(swap(*a, *b))
还不够?
这些是 noexcept()
的不同重载还是什么?
最佳答案
这不是“递归”noexcept
,noexcept
关键字有两种用法:
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/