weak_from_this
C++(11):weak_from_this从对象内部获取weak_ptr_weak from this-CSDN博客
class A
{
int test()
{auto b = std::make_shared<B>();b->pter_ = this->weak_from_this();}
};class B
{
std::weak_ptr<A> pter_;
};
#include <memory>
#include <iostream>
using namespace std;class A : public ::enable_shared_from_this<A>
{
public:~A(){cout << "Destruct A" <<endl;}weak_ptr<A> getWeak(){return weak_from_this();}
};int main()
{shared_ptr<A> sp1(new A());cout << "sp1.use_count() = " << sp1.use_count() << endl;shared_ptr<A> sp2 = sp1->getWeak().lock();if(sp2 != nullptr){cout << "sp2.use_count() = " << sp2.use_count() << endl;}return 0;
}