public member function
<memory>

std::weak_ptr::swap

void swap (weak_ptr& x) noexcept;
交換內容
將 weak_ptr 物件的內容與 x 的內容進行交換,交換它們的所有權組和任何儲存的資料。

引數

x
同一型別的另一個 weak_ptr 物件(即具有相同的類模板引數T).

返回值



示例

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;
}

輸出
sp1 -> 10
sp2 -> 20
wp1 -> 20
wp2 -> 10


另見