c++智能指针(1)

根据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);
}
上一篇:php大力力 [036节] 后台系统的登录页面界面做完啦


下一篇:cocos2dx实现android的对讯飞语音的合成(语言朗读的实现)