std::enable_shared_from_this::shared_from_this
shared_ptr<T> shared_from_this(); | (1) | |
---|---|---|
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
私人可变std::weak_ptr<T>
成员enable_shared_from_this
...
注记
它被允许打电话shared_from_this
仅在以前共享的对象上,即在std::shared_ptr
。否则,在C++17%29之前,该行为是未定义的%28。std::bad_weak_ptr
由共享引发%28。[医]来自默认构造的PTR构造函数weak_this
%29%28自C++17%29。
返回值
std::shared_ptr<T>
拥有*this
先存std::shared_ptr
S.
例
二次
#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
二次
另见
shared_ptr (C++11) | smart pointer with shared object ownership semantics (class template) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com