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获得指针
相关文章推荐
- boost准模板库scoped_ptr指针的使用以及auto_ptr智能指针的对照
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- 正确使用 std::auto_ptr 智能指针
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- C/C++:智能指针原理(运算符重载)、使用auto_ptr<A>
- C++中的auto_ptr智能指针的作用及使用方法详解
- 智能指针的模拟实现 auto_ptr scoped_ptr shared_ptr
- 智能指针auto_ptr使用注意事项
- boost 智能指针auto_ptr scoped_ptr shared_ptr scoped_array shared_array 总结
- 智能指针的模拟实现 auto_ptr scoped_ptr shared_ptr
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- C++:浅谈c++资源管理以及对[STL]智能指针auto_ptr源码分析,左值与右值
- Boost scoped_ptr scoped_array 以及scoped_ptr与std::auto_ptr对比
- C++智能指针auto_ptr的原理及使用
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- 模拟实现auto_ptr、scoped_ptr、shared_ptr等智能指针
- 智能指针:模拟实现auto_ptr,scoped_ptr,shared_ptr
- 智能指针:模拟实现auto_ptr,scoped_ptr,shared_ptr
- Boost学习笔记(一)----scoped_ptr智能指针的使用
- 智能指针auto_ptr使用注意事项