public member function
<string>

std::basic_string::swap

void swap (basic_string& str);
Swap string values
Exchanges the content of the container by the content of str, which is another basic_string object of the same type. Lengths may differ.

After the call to this member function, the value of this object is the value str had before the call, and the value of str is the value this object had before the call.

Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.

No specifics on allocators.
Whether the container allocators are also swapped is not defined, unless in the case the appropriate allocator traits indicate explicitly that they shall propagate.

Parameters

str
Another basic_string object of the same type (i.e., instantiated with the same template parameters, charT, traits and Alloc), whose value is swapped with that of this basic_string.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// swap strings
#include <iostream>
#include <string>

main ()
{
  std::string buyer ("money");
  std::string seller ("goods");

  std::cout << "Before the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  seller.swap (buyer);

  std::cout << " After the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  return 0;
}

Output:
Before the swap, buyer has money and seller has goods
 After the swap, buyer has goods and seller has money


Complexity

Constant.

Iterator validity

Any iterators, pointers and references related to this object and to str may be invalidated.

Data races

Both the object and str are modified.

Exception safety

If the allocators in both strings compare equal, or if their allocator traits indicate that the allocators shall propagate, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

See also