← Patterns
            
        Swap values
| 1234567891011 | #include <utility>
#include <string>
int main()
{
  std::string s1 = "Hello";
  std::string s2 = "World";
  using std::swap;
  swap(s1, s2);
} | 
This pattern is licensed under the CC0 Public Domain Dedication.
              Requires
              c++98
              or newer.
  
            
            Intent
Swap the values of two objects.
Description
On lines 6–7, we 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, we 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).