std::basic_string<CharT,Traits,Allocator>::swap
来自cppreference.com
                    
                                        
                    < cpp | string | basic string
                    
                                                            
                    |   void swap( basic_string& other );  | 
(C++17 前) | |
|   void swap( basic_string& other ) noexcept(/* 见下文 */);  | 
 (C++17 起)  (C++20 前)  | 
|
|   constexpr void swap( basic_string& other ) noexcept(/* 见下文 */);  | 
(C++20 起) | |
交换字符串与 other 的内容。所有迭代器和引用都可能会失效。
| 
 
如果   | 
(C++11 起) | 
参数
| other | - | 要与之交换内容的字符串 | 
返回值
(无)
复杂度
常数。
异常
| 
 不会抛出异常  | 
(C++11 前) | 
| 
 只有在行为未定义的情况下(见上文)才有可能会抛出异常。 如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。  | 
(C++11 起) | 
| 
 noexcept 说明:  
 
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value || std::allocator_traits<Allocator>::is_always_equal::value)  | 
(C++17 起) | 
示例
运行此代码
#include <iostream> #include <string> int main() { std::string a = "AAA"; std::string b = "BBBB"; std::cout << "交换前:\n" "a = " << a << "\n" "b = " << b << "\n\n"; a.swap(b); std::cout << "交换后:\n" "a = " << a << "\n" "b = " << b << '\n'; }
输出:
交换前: a = AAA b = BBBB 交换后: a = BBBB b = AAA
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 | 
|---|---|---|---|
| LWG 403 | C++98 |  swap() 可能会抛出异常
 | 
不会抛出异常 | 
| LWG 535 | C++98 | 交换字符串不会保留字符顺序 | 也保留字符顺序 |