public member function
<memory>

std::weak_ptr::lock

shared_ptr<element_type> lock() const noexcept;
鎖定並恢復 weak_ptr
如果 weak_ptr 物件未 過期,則返回一個保留了 weak_ptr 物件資訊的 shared_ptr

如果 weak_ptr 物件已過期(包括它是 空的),則函式返回一個 空的 shared_ptr(如同 預設構造 的)。

由於 shared_ptr 物件 計數 為所有者,此函式會鎖定 所擁有指標,防止其被釋放(至少在返回的物件不釋放它之前)。

此操作是原子執行的。

引數



返回值

如果物件是 weak_ptr::expired,則返回一個 預設構造的 shared_ptr 物件。
否則,返回一個 shared_ptr 物件,其中包含由 weak_ptr 保留的資訊。

示例

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

int main () {
  std::shared_ptr<int> sp1,sp2;
  std::weak_ptr<int> wp;
                                       // sharing group:
                                       // --------------
  sp1 = std::make_shared<int> (20);    // sp1
  wp = sp1;                            // sp1, wp

  sp2 = wp.lock();                     // sp1, wp, sp2
  sp1.reset();                         //      wp, sp2

  sp1 = wp.lock();                     // sp1, wp, sp2

  std::cout << "*sp1: " << *sp1 << '\n';
  std::cout << "*sp2: " << *sp2 << '\n';

  return 0;
}

輸出
*sp1: 20
*sp2: 20


另見