public member function
<string>

std::string::swap

void swap (string& str);
Swap string values
Exchanges the content of the container by the content of str, which is another string object. 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.

Parameters

str
Another string object, whose value is swapped with that of this 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

No-throw guarantee: this member function never throws exceptions.

See also