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

Exchanges the contents of the string with those of other. All iterators and references may be invalidated.

# Declarations

void swap( basic_string& other );

(until C++17)

void swap( basic_string& other ) noexcept(/* see below */);

(since C++17) (constexpr since C++20)

# Parameters

# Example

#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';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 403C++98swap() might throw an exceptionno exception is thrown
LWG 535C++98swapping strings did not preserve the character ordersorders are also preserved
LWG 2151(P1148R0)C++11no exception was thrown in the caseof unequal non-propagating allocatorsthe behavior isundefined in this case

# See also