转载自http://blog.csdn.net/salutlu/article/details/12515877
陈硕的muduo代码库的里面的TcpConnection用到了enable_shared_from_this这个基类,今天查了一下,这个基类提供了一个shared_from_this()公用方法可以让子类内部获取到shared_ptr的对象,用来用在类实现过程中需要传递自身指针的地方。有几个点需要注意一下:
1.虽然enable_shared_from_this是基类,但它确实在shared_ptr里面初始化enable_shared_from_this的成员weak_ptr。因此不能在子类的构造方法里面调用shared_from_this(),因为这个时候weak_ptr还是空值。
2.为什么在类的内部不直接使用this指针,因为我们程序中用shared_ptr来管理指针,如果我们在类的内部传递的过程中用原始指针,这样类内部的引用shared_ptr不会察觉到,因为有可能我们传进去的时候已经被shared_ptr释放掉了。
3.shared_from_this()在一个类中需要传递类对象本身shared_ptr的地方使用shared_from_this函数来获得指向自身的shared_ptr,它是enable_shared_from_this<T>的成员函数,返回shared_ptr<T>。
首先需要注意的是:这个函数仅在shared_ptr<T>的构造函数被调用之后才能使用。原因是enable_shared_from_this::weak_ptr并不在enable_shared_from_this<T>构造函数中设置,而是在shared_ptr<T>的构造函数中设置。
关于这个问题有几篇文章介绍的很详细:
http://monkeycn.iteye.com/blog/1135901
http://blog.csdn.net/huang_xw/article/details/8549444
http://www.cnblogs.com/livingintruth/archive/2012/03/05/2367253.html
http://hi.baidu.com/cpuramdisk/item/7c2f8d77385e0f29d7a89cf0
http://blog.csdn.net/rain_qingtian/article/details/10829249