gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:56:22 26 4
gpt4 key购买 nike

标准库定义了数组和 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com