名稱空間
變體
操作

std::weak_ptr<T>::lock

來自 cppreference.com
< cpp‎ | 記憶體‎ | weak ptr
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
std::shared_ptr<T> lock() const noexcept;
(C++11 起)

建立一個新的 std::shared_ptr,它共享被管理物件的所有權。如果沒有被管理物件,即 *this 為空,則返回的 shared_ptr 也為空。

有效地返回 expired() ? shared_ptr<T>() : shared_ptr<T>(*this),原子地執行。

目錄

[編輯] 引數

(無)

[編輯] 返回值

如果 std::weak_ptr::expired 返回 false,則返回一個共享被管理物件所有權的 shared_ptr。否則返回預設構造的 T 型別 shared_ptr

[編輯] 注意

此函式和 std::shared_ptr 的建構函式都可以用於獲取由 std::weak_ptr 引用的被管理物件的臨時所有權。不同之處在於,當其 std::weak_ptr 引數為空時,std::shared_ptr 的建構函式會丟擲異常,而 std::weak_ptr<T>::lock() 則構造一個空的 std::shared_ptr<T>

[編輯] 示例

#include <iostream>
#include <memory>
 
void observe(std::weak_ptr<int> weak)
{
    if (auto p = weak.lock())
        std::cout << "\tobserve() is able to lock weak_ptr<>, value=" << *p << '\n';
    else
        std::cout << "\tobserve() is unable to lock weak_ptr<>\n";
}
 
int main()
{
    std::weak_ptr<int> weak;
    std::cout << "weak_ptr<> is not yet initialized\n";
    observe(weak);
 
    {
        auto shared = std::make_shared<int>(42);
        weak = shared;
        std::cout << "weak_ptr<> is initialized with shared_ptr\n";
        observe(weak);
    }
 
    std::cout << "shared_ptr<> has been destructed due to scope exit\n";
    observe(weak);
}

輸出

weak_ptr<> is not yet initialized
        observe() is unable to lock weak_ptr<>
weak_ptr<> is initialized with shared_ptr
        observe() is able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit
        observe() is unable to lock weak_ptr<>

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2316 C++11 lock() 未要求是原子操作,但要求是 noexcept,這導致了矛盾 指定為原子操作

[編輯] 參閱

檢查引用的物件是否已被刪除
(public 成員函式) [編輯]