weak_ptr<T>
weak_from_this() noexcept; // (1) C++17
constexpr weak_ptr<T>
weak_from_this() noexcept; // (1) C++26
weak_ptr<const T>
weak_from_this() const noexcept; // (2) C++17
constexpr weak_ptr<const T>
weak_from_this() const noexcept; // (2) C++26
概要
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
処理系
- GCC: 7.3 ✅
- Clang: 3.9 ✅
- Visual C++: ??