您的位置:首页 > 运维架构

boost准模板库scoped_ptr指针的使用以及auto_ptr智能指针的对比

2014-04-20 23:46 417 查看
首先我们看看scoped_ptr的基本使用,包含了swap(),get(),reset()的使用,重要的提醒是作用域结束的时候会自动析构,无需手动的释放资源:
#include<boost/smart_ptr.hpp>
#include<iostream>
using namespace std;
using namespace boost;
struct posix_file
{
posix_file(const char * file_name)//一个文件类
{
cout<<"open file"<<file_name<<endl;//构造函数模拟打开文件
}
~posix_file()//析构函数模拟关闭文件
{
cout<<"close file"<<endl;
}
};
int main()
{
scoped_ptr<int> p(new int);//一个指向int变量的指针的scoped_ptr
if(p)//在bool语境中测试指针是否有效
{
*p=10;//像一般指针一样使用解指针操作符*
cout<<*p<<endl;
}
scoped_ptr<int> q(new int);//创建新的int指针的scoped_ptr
*q=20;
p.swap(q);//交换两个scoped_ptr指向的对象
cout<<"p value:"<<*p<<endl<<"q value:"<<*q<<endl;
p.reset();//置空scoped_ptr

if(!p)
{
cout<<"scoped==null"<<endl;
scoped_ptr<posix_file> fp(new posix_file("/temp/a.txt"));//局部scoped_ptr在作用域结束的时候自己析构
}
getchar();
}
运行结果如下:接下来,让我们看一看auto_ptr和scoped_ptr之间的联系和区别,同时,学者使用两者之间的指针控制权力转移代码示例如下:
#include<boost/scoped_ptr.hpp>
#include<iostream>
using namespace std;
using namespace boost;
int main()
{
auto_ptr<int> auto_p(new int(10));//一个int自动指针
cout<<"auto_p value:"<<*auto_p<<endl;
scoped_ptr<int> sp(auto_p);//从自动指针auto_ptr获得原始指针
if(auto_p.get()==0)//原auto_ptr不再拥有指针
cout<<"auto_p不再拥有指针"<<endl;
cout<<"sp value:"<<*sp<<endl;
auto_p.reset(new int(20));//auto_ptr获得新指针
cout<<"auto_p<-->sp:"<<*auto_p<<"<-->"<<*sp<<endl;
auto_ptr<int> auto_p2;
auto_p2=auto_p;//auto_p2获得auto_p的原始指针,auto_p失去原始指针
if(auto_p.get()==0)
{
cout<<"auto_p失去指针!"<<endl;
}
cout<<"auto_p2 value:"<<*auto_p2<<endl;
//auto_ptr<int> auto_p3(sp);//auto_ptr无法取得scoped_ptr的指针
//cout<<"auto_p3:"<<*auto_p3<<endl;
//if(auto_p2.get()==0)//
//{
//	cout<<"auto_ptr的auto_p2失去指针"<<endl;
//}//
//cout<<""<<*sp2<<endl;
//sp2=sp;编译出错,无法相互赋值
getchar();
}
下面是运行结果,可以看出auto_ptr和auto_ptr可以相互移交指针,但是scoped_ptr可以从auto_ptr获得指针而不能反向从scoped_tr获得指针

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