boost准模板库scoped_ptr指针的使用以及auto_ptr智能指针的对照
2014-11-02 10:33
483 查看
首先我们看看scoped_ptr的基本使用,包括了swap(),get(),reset()的使用,重要的提醒是作用域结束的时候会自己主动析构,无需手动的释放资源:
接下来,让我们看一看auto_ptr和scoped_ptr之间的联系和差别,同一时候,学者使用两者之间的指针控制权力转移
代码示比例如以下:
#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(); }执行结果例如以下:
#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获得指针
相关文章推荐
- boost准模板库scoped_ptr指针的使用以及auto_ptr智能指针的对比
- 智能指针auto_ptr的使用
- auto_ptr智能指针使用总结
- 详解C++各种智能指针: auto_ptr, shared_ptr, weak_ptr, scoped_ptr
- 智能指针:模拟实现auto_ptr,scoped_ptr,shared_ptr
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
- 正确使用 std::auto_ptr 智能指针
- boost库:智能指针(auto_ptr、scoped_ptr、shared_ptr)浅谈
- 几种智能指针的比较(std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::weak_ptr)
- 智能指针的模拟实现 auto_ptr scoped_ptr shared_ptr
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- 智能指针auto_ptr使用注意事项
- auto_ptr,shared_ptr 智能指针的使用
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- Boost学习笔记(一)----scoped_ptr智能指针的使用
- 智能指针auto_ptr使用注意事项
- 模拟实现智能指针auto_ptr,scoped_ptr,shared_ptr
- C++中的auto_ptr智能指针的作用及使用方法详解
- 智能指针:模拟实现auto_ptr,scoped_ptr,shared_ptr