std::weak_ptr<T>::lock
来自 cppreference.cn
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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2316 | C++11 | lock() 不需要是原子的,但需要是 noexcept,这导致了矛盾 | 指定为原子的 |
[编辑] 参见
检查引用的对象是否已被删除 (公共成员函数) |