c++智能指针(1)
2024-10-15 10:28:32
根据muduo开源库作者陈硕的一些文章。对于多线程下C++编程提出了一些观点。主要是多线程下对象的销毁比较困难,但是由于多线程下,mutext是无法保护析构的。而后提出了智能指针的方案并对使用该指针会遇到的困难和陷阱予以说明并提出解决方案。
该作者博客
http://www.cppblog.com/Solstice/
这里主要说说shared_ptr,采用计数方案,计数为零则自动删除对象,不必自己调用delete。可以使用unique()及user_count()判断该指针是否唯一指针获取者,以及指针计数。
示例如下:
#include <iostream>
#include <memory>
#include <string>
#include <set>
#include <map>
#include <boost/smart_ptr.hpp>
#include <assert.h> using std::set;
using std::string;
using std::cout;
using std::endl;
using std::map;
using std::pair; int main()
{
boost::shared_ptr<int> num(new int()); cout << "num: " << *num << endl; cout << "use_count: " << num.use_count() << endl; assert( num.unique()); cout << "is unique() " << num.unique() << endl; boost::shared_ptr<int> num2 = num; cout << "use_count: " << num.use_count() << endl;
cout << "use_count2: " << num2.use_count() << endl; boost::shared_ptr<int> spi = boost::make_shared<int>();
cout << endl;
cout << "make_shared " << *spi << endl; return ;
}
与auto_ptr比较 , shared_ptr可以在容器中使用
#include <iostream>
#include <string>
#include <boost/smart_ptr.hpp>
#include <vector> using std::string;
using std::cout;
using std::endl;
using std::vector;
using boost::shared_ptr;
using boost::make_shared; int main()
{
typedef vector<shared_ptr<int> > v_sp;
v_sp v(); int i = ;
for(v_sp::iterator pos = v.begin(); pos != v.end(); ++pos)
{
(*pos) = make_shared<int>(++i);
} for(v_sp::iterator pos = v.begin(); pos != v.end(); ++pos)
{
cout << "value: " << *(*pos) << endl;
cout << "use_count: " << (*pos).use_count() << endl;
cout << endl;
} cout << endl; shared_ptr<int> p(v[]);
cout << "value: " << *p << endl;
cout << "use_count: " << p.use_count() << endl; // 此刻有两个shared_ptr指向该值 return ;
}
创建智能指针的时候 可以指定释放函数
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <windows.h> using namespace std; HRESULT MyCloseHandle(HANDLE hHandle )
{
cout << "Enter CloseHandle func" << endl;
return CloseHandle(hHandle);
} int main()
{
cout << "Start create shared_ptr for handle " << endl;
boost::shared_ptr<void> h(OpenProcess(PROCESS_SET_INFORMATION, FALSE, GetCurrentProcessId()), MyCloseHandle);
cout << "Create shared_ptr for handle finish" << endl;
SetPriorityClass(h.get(), HIGH_PRIORITY_CLASS);
}
最新文章
- Asp.Net Core 项目实战之权限管理系统(4) 依赖注入、仓储、服务的多项目分层实现
- linux 查看端口号
- zendFream 中的用到了Ajax(其中有搜索)分页
- JAVA基础知识之JDBC——编程步骤及执行SQL
- 44. 普通对象建一个用户方法,提交时报:失败:建立业务逻辑对象失败:业务逻辑定义更新到数据库失败:ORA-00904: ";DEFVERSION";: 标识符无效
- java.lang.UnsupportedClassVersionError: xxx/xxxClass : Unsupported major.minor version 51.0
- 【extjs】 ext5 Ext.grid.Panel 分页,搜索
- WebRtc VoiceEngine代码解析
- Lotus 迁移到Exchange 2010 之准备使用Transport 同步Lotus 相关信息!
- linux虚拟机centos64位_6.5+VM10安装oracle11g图文详解
- Android笔记二十四.Android基于回调的事件处理机制
- asp.net core 五 SignalR 负载均衡
- Spring的核心模块解析
- hisi35xx串口驱动的完善
- opencv 替换图像中的一部分
- 吴裕雄 31-MySQL 导出数据
- eclipse下创建maven项目并部署到tomcat服务器(转)
- 使用psutil库监控linux的系统资源和自定义进程的cpu 内存占用。
- 把握这两点,抢占下一个电商风口|2016最新中国电商App排名&;研究报告
- Spring bean加载2--FactoryBean情况处理