名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
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>::
    propagate_on_container_swap::value &&
get_allocator() == s.get_allocator()
false,則行為未定義。

(C++11 起)

目錄

[編輯] 引數

其他 - 要交換內容的字串

[編輯] 複雜度

常數時間。

[編輯] 異常

不丟擲任何異常。

(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 << "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

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 403 C++98 swap() 可能丟擲異常 不丟擲異常
LWG 535 C++98 交換字串不保留字元順序 順序也保留
LWG 2151
(P1148R0)
C++11 在這種情況下不丟擲異常
對於不相等的非傳播分配器
在這種情況下,行為是
未定義的

[編輯] 另請參閱

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