在线文档教程
C++
应用 | Utilities

std::weak_ptr::lock

性病:弱[医]PTR::LOCK

std::shared_ptr 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>...

二次

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

二次

产出:

二次

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++标准。

DRApplied toBehavior as publishedCorrect behavior
LWG 2316C++11lock() was not required to be atomic, but required to be noexcept, which led to a contradictionspecified to be atomic

另见

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

© cppreference.com

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

http://en.cppreference.com/w/cpp/Memory/WILE[医]PTR/锁