【涨姿势】shared_from_this

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释放掉了。

关于这个问题有几篇文章介绍的很详细:

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


【转自:http://blog.csdn.net/salutlu/article/details/12515877】


你可能感兴趣的:(【涨姿势】shared_from_this)