std::swap(std::basic_string)
来自 zh.cppreference.net
| 定义于头文件 <string>
|
||
template< class CharT, class Traits, class Alloc >
void swap( std::basic_string<CharT, Traits, Alloc>& lhs,
std::basic_string<CharT, Traits, Alloc>& rhs );
|
(直到 C++17) | |
template< class CharT, class Traits, class Alloc >
void swap( std::basic_string<CharT, Traits, Alloc>& lhs,
std::basic_string<CharT, Traits, Alloc>& rhs ) noexcept(/* see below */);
|
(自 C++17起) (自 C++20起 constexpr) |
|
特化 std::swap 算法用于 std::basic_string。交换 lhs 与 rhs 的内容。
等价于 lhs.swap(rhs)。
参数
| lhs, rhs | - | 要交换内容的字符串 |
返回值
(无)
复杂度
常量。
异常
noexcept
规范:
noexcept
(
noexcept
(
lhs.
swap
(
rhs
)
)
)
|
(C++17 起) |
示例
运行此代码
#include <iostream> #include <string> int main() { std::string a = "AAA"; std::string b = "BBBB"; std::cout << "Before swap:\n" "a = " << a << "\n" "b = " << b << "\n\n"; std::swap(a, b); std::cout << "After swap:\n" "a = " << a << "\n" "b = " << b << '\n'; }
输出:
Before swap: a = AAA b = BBBB After swap: a = BBBB b = AAA
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| DR | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2064 | C++11 |
非成员
swap
带有 noexcept 且与成员
swap
不一致
|
移除 noexcept |
参见
|
交换内容
(公开成员函数) |