Namespaces
Variants

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

From ja.cppreference.net
 
 
 
std::basic_string
 
void swap( basic_string& other );
(C++17未満)
void swap( basic_string& other ) noexcept(/* see below */);
(C++17以上)
(C++20 より constexpr)

文字列の内容を other の内容と交換します。すべてのイテレータと参照は無効化される可能性があります。

もし std::allocator_traits<allocator_type>::propagate_on_container_swap::value が true の場合、アロケータは非メンバの 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 << "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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 403 C++98 swap() が例外を送出する可能性があった 例外は送出されない
LWG 535 C++98 文字列の交換で文字の順序が保持されなかった 順序も保持される
LWG 2151
( P1148R0 )
C++11 非伝播アロケータが異なる場合に
例外が送出されなかった
この場合の動作は
未定義である

関連項目

2つのオブジェクトの値を交換する
(関数テンプレート)
2つの範囲の要素を交換する
(関数テンプレート& アルゴリズム関数オブジェクト)
内容を交換する
(std::basic_string_view<CharT,Traits>のパブリックメンバ関数)