boost::enable_shared_from_this
2016-07-20 10:55
232 查看
boost::enable_shared_from_this
这个类能够让一个被
shared_ptr管理生命周期的类能够在自己的成员函数内部使用自己的
shared_ptr。
在什么场景下需要使用一个
shared_ptr呢?直接使用this指针不行吗?
想象一下这样的场景:在类中发起一个异步操作,回调函数callback在被调用时要保证发起操作的对象仍然存在。那么使用this是不合适的,因为它有可能已经析构了。而使用
shared_ptr则能够保证对象的引用计数至少为1,这也就保证了对象仍然有效。
举个例子:
在不使用
boost::enable_shared_from_this时,在自己的成员函数获取自身的
shared_ptr成了问题,如下例所示:
#include <iostream> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> using namespace std; class Foo { public: Foo() : n_(8) { cout << "ctor" << endl; } ~Foo(){ cout << "dtor" << endl; } void DoSomething() { boost::shared_ptr<Foo> sp(this); cout << n_ << endl; } private: int n_; }; int main() { boost::shared_ptr<Foo> f(new Foo); f->DoSomething(); return 0; }
这种用法是错误的,一个对象被两个智能指针管理,很明显,析构函数会被调用两次:
ctor 8 dtor dtor
这时需要使用
boost::enable_shared_from_this:
class Foo2 : public boost::enable_shared_from_this<Foo2> { public: Foo2() : n_(8) { cout << "ctor" << endl; } ~Foo2(){ cout << "dtor" << endl; } void DoSomething() { boost::shared_ptr<Foo2> sp = shared_from_this(); cout << n_ << endl; } boost::shared_ptr<Foo2> GetPointer() { return shared_from_this(); } private: int n_; }; int main() { boost::shared_ptr<Foo2> f(new Foo2); f->DoSomething(); cout << "use count:" << f.use_count() << endl; boost::shared_ptr<Foo2> t = f->GetPointer(); cout << "use count:" <<f.use_count() << endl; return 0; }
输出:
ctor 8 use count:1 use count:2 dtor
相关文章推荐
- 关于NSDate的那些事儿
- CountDownLatch
- 线性回归
- mysql 里面的isnull()和ifnull() is null 和 is not null
- CENTOS单用户下修改密码报“passwd: Authentication Token Manipulation Error”
- 对象持久化
- php设计模式学习之单例模式
- 数据库中的左连接(left join)和右连接(right join)区别
- 【做减法】Linux工具快速教程 - 基础篇
- opencv-霍夫线变换
- Eclipse 变量 类 方法明注释快捷键
- Ajax开发步骤解析
- CentOS6.5安装oracle11g release2记录
- UVA 113-Power of Cryptography
- 【webapp的优化整理】要做移动前端优化的朋友进来看看吧
- [置顶] Android N7.0多窗口适配开发指导
- HDU 5724 Chess
- Balanced Binary Tree
- android使用PullToRefresh实现上拉加载和下拉刷新效果
- 在 Ubuntu Mate 16.04 上通过 PPA 升级 Mate 1.14