std::basic_string<CharT,Traits,Allocator>::swap
来自 cppreference.cn
< cpp | string | basic string
void swap( basic_string& other ); |
(until C++17) | |
void swap( basic_string& other ) noexcept(/* see below */); |
(since C++17) (constexpr since C++20) |
|
与 other 交换字符串的内容。所有迭代器和引用都可能失效。
如果 std::allocator_traits<Allocator>:: |
(since C++11) |
目录 |
[edit] 参数
other | - | 与其交换内容的字符串 |
[edit] 复杂度
常量。
[edit] 异常
不抛出异常。 |
(until C++11) |
不抛出异常,除非行为未定义。 如果由于任何原因抛出异常,则此函数无效(强异常安全保证)。 |
(since C++11) |
noexcept 规范:
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value || std::allocator_traits<Allocator>::is_always_equal::value) |
(since C++17) |
[edit] 示例
运行此代码
#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"; a.swap(b); std::cout << "After swap:\n" "a = " << a << "\n" "b = " << b << '\n'; }
输出
Before swap: a = AAA b = BBBB After swap: a = BBBB b = AAA
[edit] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 403 | C++98 | swap() 可能抛出异常 |
不抛出异常 |
LWG 535 | C++98 | 交换字符串不会保留字符顺序 | 顺序也被保留 |
LWG 2151 (P1148R0) |
C++11 | 在以下情况下未抛出异常 不相等非传播分配器 |
此情况下的行为是 未定义的 |
[edit] 参见
交换两个对象的值 (函数模板) | |
交换两个元素范围 (函数模板) | |
swaps the contents (public member function of std::basic_string_view<CharT,Traits> ) |