std::weak_ptr<T>:: lock
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Modifiers | ||||
| Observers | ||||
|
weak_ptr::lock
|
||||
|
(C++26)
|
||||
|
(C++26)
|
||||
| Non-member functions | ||||
| Helper classes | ||||
|
(C++20)
|
||||
| Deduction guides (C++17) |
|
std::
shared_ptr
<
T
>
lock
(
)
const
noexcept
;
|
(C++11以降) | |
管理対象オブジェクトの所有権を共有する新しい
std::shared_ptr
を作成します。管理対象オブジェクトが存在しない場合、すなわち
*
this
が空の場合、返される
shared_ptr
も空となります。
実質的に expired ( ) ? shared_ptr < T > ( ) : shared_ptr < T > ( * this ) を返し、アトミックに実行されます。
目次 |
戻り値
所有権を持つオブジェクトの所有権を共有する
shared_ptr
を返す。ただし、
std::weak_ptr::expired
が
false
を返す場合に限る。それ以外の場合は、型
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 であることが要求されており、矛盾が生じていた | アトミックであることが規定された |
関連項目
|
参照先のオブジェクトが既に削除されているかどうかをチェックする
(public member function) |