Namespaces
Variants

std::weak_ptr<T>:: lock

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
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::shared_ptr 构造函数的 std::weak_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,这导致了矛盾 规定为原子操作

参见

检查被引用的对象是否已被删除
(公开成员函数)