Boost:使用shared_array和shared_ptr

13 篇文章 0 订阅

转自: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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值