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

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
Modifiers
basic_string::swap
Search
Operations
(哋它亢++23)
Constants
Non-member functions
I/O
Comparison
(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(until 哋它亢++20)(哋它亢++20)
Numeric conversions
(哋它亢++11)(哋它亢++11)(哋它亢++11)
(哋它亢++11)(哋它亢++11)
(哋它亢++11)(哋它亢++11)(哋它亢++11)
(哋它亢++11)
(哋它亢++11)
Literals
(哋它亢++14)
Helper classes
Deduction guides (哋它亢++17)

 
void swap( basic_string& other );
(until 哋它亢++17)
void swap( basic_string& other ) noexcept(/* see below */);
(since 哋它亢++17)
(constexpr since 哋它亢++20)

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

The behavior is undefined if Allocator does not propagate on swap and the allocators of *this and other are unequal.

(since 哋它亢++11)

Parameters

other - string to exchange the contents with

Return value

(none)

Complexity

Constant.

Exceptions

No exception is thrown.

(until 哋它亢++11)

Exceptions can only be thrown in the case where the behavior is undefined (see above).

If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee).

(since 哋它亢++11)


noexcept specification:  
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value ||
         std::allocator_traits<Allocator>::is_always_equal::value)
(since 哋它亢++17)

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

Output:

Before swap:
a = AAA
b = BBBB
 
After swap:
a = BBBB
b = AAA

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published 哋它亢++ standards.

DR Applied to Behavior as published Correct behavior
LWG 403 哋它亢++98 swap() might throw an exception no exception is thrown
LWG 535 哋它亢++98 swapping strings did not preserve the character orders orders are also preserved

See also

swaps the values of two objects
(function template)
swaps two ranges of elements
(function template)
swaps the contents
(public member function of std::basic_string_view<CharT,Traits>)