首页 > 代码库 > boost 学习

boost 学习

智能指针的学习

中文教程网站 http://zh.highscore.de/cpp/boost/

不过代码可能 由于BOOST 版本不同需要稍作修改

 

scoped_ptr 离开作用域则自动调用类析构函数或者函数delete方法

shared_ptr 使用率最高的指针 类似scoped_ptr 但是所有权可以转移

 

#include <iostream>#include <vector>#include <windows.h>#include <boost/smart_ptr.hpp>using namespace std;class CHandle{	HANDLE hProcess;public:	CHandle() { hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, GetCurrentProcessId()); }	~CHandle() { cout << "Enter destructor handle" << endl; if(NULL != hProcess){CloseHandle(hProcess);hProcess = NULL;} }	void PrintHandle() {cout << hProcess << endl;}};int _tmain(int argc, _TCHAR* argv[]){	{		boost::scoped_ptr<CHandle> sp(new CHandle);		sp->PrintHandle();		sp.reset(new (CHandle));		sp->PrintHandle();	}	cout << endl;		typedef boost::shared_ptr<int> SHP;	vector<SHP> v;	v.push_back(SHP (new int(1)));	v.push_back(SHP (new int(2)));	v.push_back(SHP (new int(3)));	for(vector<SHP>::iterator it = v.begin();		it != v.end();++it)	{		cout << *(*it) << endl;	}	cout << endl;		boost::shared_ptr<int> i1(new int(99)); 	boost::shared_ptr<int> i2(i1);   	cout << *i1 << endl;	cout << *i2 << endl;	i1.reset(new int(5));  	cout << *i1 << endl;	cout << *i2 << endl;		return 0;}

  

 再来一个示例

智能指针创建空间 保存输入的字符串

int _tmain(int argc, _TCHAR* argv[]){	char sz[] = "this is  test string";	int strLen = strlen(sz) + 1;	typedef boost::shared_ptr<char> SHPCHAR;	SHPCHAR szp(new char[strLen]);	strncpy(szp.get(),sz,strLen);	cout << szp.get() <<endl;		return 0;}