std::enable_shared_from_this<T>::shared_from_this
std::shared_ptr<T> shared_from_this(); (1)
std::shared_ptr<T const> shared_from_this() const; (2)
返回一个 std::shared_ptr<T>
,该指针与所有指向 *this
的现有 std::shared_ptr 共享对 *this
的所有权。
有效地执行 std::shared_ptr<T>(weak_this)
,其中 weak_this
是 enable_shared_from_this 的私有可变 std::weak_ptr<T>
成员。
备注
仅允许在先前已共享的对象上调用 shared_from_this,即在由 std::shared_ptr 管理的对象上调用(特别是,在构造 *this
期间不能调用 shared_from_this)。
否则行为是未定义的(直到 C++17)/ 抛出 std::bad_weak_ptr(由从默认构造的 weak_this 构造的 shared_ptr)(自 C++17 起).
返回值
std::shared_ptr<T>
,它与预先存在的 std::shared_ptrs 共享对 *this
的所有权
示例
注意:enable_shared_from_this::operator=
被定义为 protected,以防止意外的切片,但允许派生类拥有默认的赋值运算符。
#include <iostream>
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
Foo *f = new Foo;
std::shared_ptr<Foo> pf1;
{
std::shared_ptr<Foo> pf2(f);
pf1 = pf2->getFoo(); // shares ownership of object with pf2
}
std::cout << "pf2 is gone\n";
}
Foo::Foo
pf2 is gone
Foo::~Foo