boost - 智能指针总结
来源:互联网 发布:蓝盾 大数据 编辑:程序博客网 时间:2024/05/11 19:11
shared_ptr
常用接口
use_count() : 获得引用计数数量。
get() : 获得原始指针。
reset() : 指向NULL内存。
注意事项
1. 不能直接赋值NULL,编译无法通过;如果需要清空使用reset();reset后,ptr指向NULL内存。
2. 不能手动释放内存,如delete ptr.get(),这将会出现内存错误,至于为什么,目前还不清楚。
3. 先分配内存,再交给智能指针,再释放也不可以,如
int * c = new int;
boost::shared_ptr<int> pObj(c);
delete c;
会出现内存错误,boost是怎么防止用户在外面delete c的呢?
weak_ptr
是执行弱引用的智能指针。当你需要它的时候就可以使用一个强(共享)指针指向它(当对象被释放的时候,它为空),当然这个强指针在使用完毕应该立即释放掉
struct CBetterChild : public CSample{ weak_ptr<CDad> myDad; void BringBeer() { shared_ptr<CDad> strongDad = myDad.lock(); // request a strong pointer if (strongDad) // is the object still alive? strongDad->SetBeer(); // strongDad is released when it goes out of scope. // the object retains the weak pointer }};
注意事项
1. 弱引用如果需要操作类对象,需要转为强引用,通过lock接口获得
2. 获得强引用后,需要检测对象是否为空,因为有可能对象已经释放
3. 操作完毕后,强引用应该马上释放,也就是强引用最好是临时局部变量
常用接口
lock() : 转为强引用,如果对象已经释放,则返回空的强引用
expired(): 判断对象是否已经释放
- boost - 智能指针总结
- Boost的智能指针
- 智能指针:boost学习
- Boost中的智能指针
- boost智能指针
- 【Boost】智能指针
- 使用Boost智能指针
- boost智能指针介绍
- Boost智能指针学习
- Boost智能指针:shared_ptr
- Boost智能指针小记
- Boost 中的智能指针
- boost:智能指针
- 使用Boost智能指针
- C++ Boost智能指针
- boost智能指针
- Boost之智能指针
- boost - 智能指针介绍
- Asp.Net数据控件引用AspNetPager.dll分页
- 多选框、单选框的使用
- struts文件下载
- 如何将DBGrid 中的数据导入到EXCEL中
- 手机、平板多屏幕多分辨率适配
- boost - 智能指针总结
- C/C++与Python互相调用
- Sublime Text 2.0.1 编辑器中使用 Source Code Pro 字体
- LDA(一)
- 模拟多个客户端IP发送udp包
- php标准库函数功能(SPL)
- 在 CentOS 上安装 CPU 温度监控软件(lm_sensors)
- eclipse和svn在windows和mac os x下使用
- storm集群安装