Skip to content

Latest commit

 

History

History
115 lines (83 loc) · 5.03 KB

weak_ptr.md

File metadata and controls

115 lines (83 loc) · 5.03 KB

weak_ptr

  • memory[meta header]
  • std[meta namespace]
  • class template[meta id-type]
  • cpp11[meta cpp]
namespace std {
  template <class T>
  class weak_ptr;
}

概要

weak_ptrは、shared_ptrオブジェクトが持つリソースへの弱参照を保持するクラスである。

このクラスは、shared_ptrオブジェクトのリソースに対する所有権は保持せず、そのリソースを監視し、覗き見する。

循環参照の解決に使用する

shared_ptrは、所有権を参照カウントで管理し、所有者がいなくなったらリソースを解放するクラスである。

しかし、参照カウントという機構には、循環参照を解決できないという問題がある。ABへのshared_ptrを保持し、BもまたAへのshared_ptrを保持する、ということをした場合、参照カウントが永遠に0にならず、リソースリークが発生する。

このような構造がどうしても必要な場合、一方はshared_ptrを保持し、一方はそのshared_ptrへのweak_ptrを保持する、というようにすることで、循環参照を解決できる。

weak_ptrは、監視対象のshared_ptrオブジェクトの参照カウントを、加算も減算もしない。

shared_ptrは、リソースを使用している間は解放されないという保証があるということも特徴の一つではあるので、weak_ptrにする対象が、リソースが参照できなくなっても問題ないか、ということを確認した上で使用すること。

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++11
(destructor) デストラクタ C++11
operator= 代入演算子 C++11
swap 他のweak_ptrオブジェクトとデータを入れ替える C++11
reset weak_ptrオブジェクトと監視対象とのリンクをクリアする C++11
use_count 監視しているshared_ptrオブジェクトの所有者数を取得する C++11
expired 監視対象の寿命切れやリンク切れを判定する C++11
lock 監視しているshared_ptrオブジェクトを取得する C++11
owner_before 所有権ベースでの小なり比較を行う C++11

メンバ型

名前 説明 対応バージョン
element_type 要素型T C++11

非メンバ関数

名前 説明 対応バージョン
swap 2つのweak_ptrオブジェクトを入れ替える C++11

推論補助

名前 説明 対応バージョン
(deduction_guide) クラステンプレートの推論補助 C++17

#include <memory>
#include <iostream>

int main()
{
  // weak_ptrオブジェクトwpは、
  // shared_ptrオブジェクトspを監視する
  std::shared_ptr<int> sp(new int(42));
  std::weak_ptr<int> wp = sp;

  // wpの監視対象であるspが、有効なリソースを保持している状態なら処理する。
  if (std::shared_ptr<int> r = wp.lock()) {
    std::cout << "get weak_ptr value : " << *r << std::endl;
  }

  sp.reset();

  // shared_ptrオブジェクトが無効になったことを検知する
  if (wp.expired()) {
    std::cout << "shared_ptr managed object deleted." << std::endl;
  }
}
  • std::weak_ptr[color ff0000]
  • wp.lock[link weak_ptr/lock.md]
  • sp.reset[link shared_ptr/reset.md]
  • wp.expired()[link weak_ptr/expired.md]

出力

get weak_ptr value : 42
shared_ptr managed object deleted.

バージョン

言語

  • C++11

処理系

参照