Namespaces
Variants

std::swap(std::basic_string)

ja.cppreference.net より
 
 
 
std::basic_string
 
ヘッダ <string>
template< class CharT, class Traits, class Alloc >
void swap( std::basic_string<CharT, Traits, Alloc>& lhs,
           std::basic_string<CharT, Traits, Alloc>& rhs );
で定義 (C++17まで)
template< class CharT, class Traits, class Alloc >
void swap( std::basic_string<CharT, Traits, Alloc>& lhs,
           std::basic_string<CharT, Traits, Alloc>& rhs ) noexcept(/* see below */);
(C++17以降)
(constexpr C++20以降)

std::swap アルゴリズムを std::basic_string に対して特殊化します。lhs と rhs の内容を交換します。

lhs.swap(rhs) と同等です。

パラメータ

lhs, rhs - 内容を交換する文字列

戻り値

(なし)

計算量

定数。

例外仕様

noexcept 仕様:
noexcept ( noexcept ( lhs. swap ( rhs ) ) )
(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";
    std::swap(a, 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 2064 C++11 非メンバー swap がnoexceptであり、メンバー swap と一貫性がなかった noexceptを削除

関連項目

内容を交換する
(公開メンバ関数)