最終更新日時(UTC):
が更新

履歴 編集

function
<memory>

std::enable_shared_from_this::weak_from_this(C++17)

weak_ptr<T> weak_from_this() noexcept;
weak_ptr<const T> weak_from_this() const noexcept;

概要

thisポインタをweak_ptrに変換する。

要件

*thisのインスタンスがshared_ptrオブジェクトとして共有されていること。

戻り値

thisポインタを指すweak_ptrオブジェクトを返す。

#include <cassert>
#include <memory>

struct X : public std::enable_shared_from_this<X> {
  std::weak_ptr<X> f()
  {
    // thisを指すweak_ptrオブジェクトを作る
    return weak_from_this();
  }
};

int main()
{
  std::shared_ptr<X> p(new X());
  std::weak_ptr<X> q = p->f();

  assert(p == q.lock());
}

出力

バージョン

言語

  • C++17

処理系

参照