解析enable_shared_from_this

来源:互联网 发布:易语言dnf辅助源码模板 编辑:程序博客网 时间:2024/05/17 23:50

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,因为此时对象尚未构造完成。