jhyatt1017
7/18/2018 - 8:48 PM

Swap values

NTENT

Swap the values of two objects.

DESCRIPTION

  • On lines 6–7, I create two std::string objects whose values we wish to swap. However, this pattern will also apply to any other swappable type.

  • On line 9, I use a using-declaration to make std::swap visible and then, on line 10, we call unqualified swap (not std::swap) to swap the values of the two objects. This allows a user-defined specialization of swap to be found via argument-dependent lookup (ADL), which may provide a more efficient implementation of the swap operation, before falling back to the generic std::swap function. This approach is particularly useful when swapping two generic objects (such as in a template).

#include <utility>
#include <string>
int main()
{
  std::string s1 = "Hello";
  std::string s2 = "World";
  using std::swap;
  swap(s1, s2);
}