首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::weak_ptr::lock

std::shared_ptr<T> lock() const;

(since C++11)

创建一个新的std::shared_ptr它共享托管对象的所有权。如果没有托管对象,即*this是空的,那么返回的shared_ptr也是空的。

有效回报expired() ? shared_ptr<T>() : shared_ptr<T>(*this)被原子处决。

参数

%280%29

返回值

shared_ptr在以下情况下,哪个共享拥有的对象的所有权?std::weak_ptr::expired回报false.否则返回默认构造的shared_ptrT型。

例外

noexcept规格:

noexcept

注记

函数和std::shared_ptr可用于获取由std::weak_ptr的不同之处在于std::shared_ptr抛出异常时,std::weak_ptr参数为空,而std::weak_ptr<T>::lock()构造空std::shared_ptr<T>...

二次

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

二次

产出:

二次

代码语言:javascript
复制
weak_ptr<> not yet initialized
        observe() unable to lock weak_ptr<>
weak_ptr<> initialized with shared_ptr.
        observe() able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit.
        observe() unable to lock weak_ptr<>

二次

缺陷报告

以下行为更改缺陷报告追溯应用于先前发布的C++标准。

DR

Applied to

Behavior as published

Correct behavior

LWG 2316

C++11

lock() was not required to be atomic, but required to be noexcept, which led to a contradiction

specified to be atomic

另见

expired

checks whether the referenced object was already deleted (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券