std::weak_ptr<T>::lock
std::shared_ptr<T> lock() const noexcept;
创建一个新的 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 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++ 标准。
DR | 应用于 | 发布时的行为 | 正确行为 |
---|---|---|---|
LWG 2316 | C++11 | lock() 原本不要求是原子的,但要求是 noexcept,这导致了矛盾。 | 指定为原子的 |