gpt4 book ai didi

c++ - 为什么 basic_string::swap 不是 noexcept?

转载 作者:IT老高 更新时间:2023-10-28 21:47:33 26 4
gpt4 key购买 nike

我刚刚发现 basic_string 的两个交换函数(成员函数和命名空间 std 中的函数)没有用 noexcept 声明——既不是在 GCC-4.8 的标准库中,也不是在最新的C++ 草案 N3690。

另一方面,移动构造函数和移动赋值运算符是用noexcept 声明的。这说明应该可以提供noexcept交换函数。

问题:没有用 noexcept 声明交换函数的原因是什么?

更新:问题是我想在我自己的交换函数中使用一个模板函数,它使用 static_assert 来检查交换实际上是 noexcept,例如:

struct foo {
bar_t bar;
baz_t baz;
void swap(foo& rhs) noexcept {
swap_noexcept(bar, rhs.bar);
swap_noexcept(baz, rhs.baz);
}
};

但是,只有在使用 noexcept 声明交换函数时才有效,而 basic_string 则不是这样。

最佳答案

C++11 标准第 21.4.6.8 段规定:

21.4.6.8 basic_string::swap [string::swap]

void swap(basic_string& s);

1 Postcondition: *this contains the same sequence of characters that was in s, s contains the same sequence of characters that was in *this.

2 Throws: Nothing.

3 Complexity: constant time.

因此,必须断定缺少 noexcept 是一种疏忽。

另一条线索在 assign() 成员函数的第 21.4.6.3 段中给出:

basic_string& assign(basic_string&& str) noexcept;

Effects: The function replaces the string controlled by *this with a string of length str.size() whose elements are a copy of the string controlled by str. [ Note: A valid implementation is swap(str). — end note ]

3 Returns: *this.

如果 swap(str) 应该是 assign() 的有效实现,并且 assign() 被标记为无条件 noexcept,那么假设 swap()noexcept 也是有意义的。

关于c++ - 为什么 basic_string::swap 不是 noexcept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629743/

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