public member function
<memory>

std::weak_ptr::swap

void swap (weak_ptr& x) noexcept;
Swap content
Exchanges the contents of the weak_ptr object with those of x, swapping their owning groups and any stored data.

Parameters

x
Another weak_ptr object of the same type (i.e., with the same class template parameter T).

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// weak_ptr::swap example
#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> sp1 (new int(10));
  std::shared_ptr<int> sp2 (new int(20));

  std::weak_ptr<int> wp1(sp1);
  std::weak_ptr<int> wp2(sp2);

  wp1.swap(wp2);

  std::cout << "sp1 -> " << *sp1 << '\n';
  std::cout << "sp2 -> " << *sp2 << '\n';
  std::cout << "wp1 -> " << *wp1.lock() << '\n';
  std::cout << "wp2 -> " << *wp2.lock() << '\n';

  return 0;
}


Output:
sp1 -> 10
sp2 -> 20
wp1 -> 20
wp2 -> 10

See also