enable_shared_from_this解析,作用,原理
直接以代码来说明:
class Connection
{
public:
void func()
{
//我们的Connection对象都被shared_ptr所管理,在这个函数中我们需要获得对象的shared_ptr.
//但是我们不能够这么写
//shared_ptr<Connection> local_sp(this),这个创建当前对象副本的另一个shared_ptr,并且引用计数是1,但是我们需要获得的是被管理的那个 //shared_ptr.
//所以有
shared_ptr<Connection> local=shared_from_this();
}
}
int main()
{
shared_ptr<Connection> Conn(new Connection);
}
这里的enable_shared_from_this利用weak_ptr实现,同时我们注意的是不要在构造函数中使用enable_shared_from_this,因为此时对象尚未构造完成。