您的位置:首页 > 编程语言 > C语言/C++

Boost:使用shared_array和shared_ptr

2013-06-03 11:12 435 查看
转自:http://hi.baidu.com/ae8506/item/7279e8cf8eb17020a1b50a55

作者:CYM

和scoped_array和scoped_ptr相比,shared_ptr和shared_array更加灵活.从他的名称可以看出他是一个共享的指针管理器.

可以毫不保留的说shared_ptr是在软件开发中最有价值的一个.非常重要.

而且shared_ptr和shared_array使用起来几乎和scoped_ptr和scoped_array几乎相同.同时更加灵活,

 

以下是使用shared_array的相关代码:他的功能是首先输出一字符串到txt文件中,然后再读取这个文件中的字符,打印到控制台..

---------------代码---------------------------

//C++常用库

#include <string>

#include <iostream>

#include <vector>

#include <set>

#include <map>

#include <algorithm>

#include <iostream>

#include <fstream>

//boost库

#include <boost/smart_ptr.hpp>

using namespace std;

using namespace boost;

void main()

{

 //输出到文件

 ofstream outFile;

 outFile.open("text.txt",ios::app);

 outFile<<"简单的测试"<<endl

  <<"------结束------"<<endl;

 outFile.close();

 //打印文件字符

 shared_array<char> text(new char[1000]);   //这里使用了shared_array指针管理器

 ifstream inFile;

 inFile.open("text.txt");

 

 assert(text);

 int i=0;

 while((text[i]=inFile.get())!=EOF)

 {

  cout<<text[i];

  ++i;

 }

 inFile.close();

 getchar();

}

 

这段代码使用了shared_array指针管理器,省去了最后的delete[] 操作..

但是我们还可以发现文件必须被手动释放,但是很多时候我们会忘记关闭文件,这时我们就需要shared_ptr指针管理器

 

使用shared_ptr和使用scoped_ptr没区别,只是多了一个参数"删除器"

只需要这样定义,当对象退出作用域时就会自动调用fclose函数来释放资源

boost::shared_ptr<FILE> inFile(fopen("text.txt","r"),fclose);

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ boost