std::weak_ptr<T>::lock
提供: cppreference.com
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> を構築します。
[編集] 例
Run this code
#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() was not required to be atomic, but required to be noexcept, which led to a contradiction | specified to be atomic |
[編集] 関連項目
参照先のオブジェクトがすでに削除されたか調べます (パブリックメンバ関数) |