std::basic_string<CharT,Traits,Allocator>::swap

出自cppreference.com
 
 
 
std::basic_string
 
void swap( basic_string& other );
(C++17 前)
void swap( basic_string& other ) noexcept(/* 见下文 */);
(C++17 起)
(C++20 起為 constexpr)

交換字符串與 other 的內容。所有迭代器和引用都可能會失效。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,那麼使用對非成員 swap 進行無限定調用來交換這些分配器。否則,不交換它們(且若 get_allocator() != other.get_allocator() 則其行為未定義)。

(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 交換字符串不會保留字符順序 也保留字符順序
LWG 2151
(P1148R0)
C++11 在分配器不相等且不傳播的情況下不會拋出異常 此時行為未定義

參閱

交換兩個對象的值
(函數模板) [編輯]
交換兩個範圍的元素
(函數模板) [編輯]
交換內容
(std::basic_string_view<CharT,Traits> 的公開成員函數) [編輯]