enable_shared_from_this是针对类中数据传出shared_ptr出现多次析构而设计的
class Test //这种情况会析构两次,有段错误
{
public:
~Test() { cout << "析构了!" << endl; }
shared_ptr<Test> GetThis()
{
return shared_ptr<Test>(this);
/ }
};
int main() {
shared_ptr<Test> p(new Test());
shared_ptr<Test> q = p->GetThis();
}
上段代码中有p通过GetThis将this传给q,因此引用指数为2,但数据只有一份,最后析构两次导致出错
对上段代码用enable_shared_from_this改造后:
class Test :public enable_shared_from_this<Test>
{
public:
~Test() { cout << "析构了!" << endl; }
shared_ptr<Test> GetThis()
{
return shared_from_this();
}
};
int main() {
shared_ptr<Test> p(new Test());
shared_ptr<Test> q = p->GetThis();
}
通过调用shared_from_this()后,析构只用了一次,不会出现段错误