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


          首先我们看看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获得指针


    
    
  • 相关阅读:
    Maven打包时过滤测试代码或指定特定的测试类(maven-surefire-plugin)
    Maven项目配置外部依赖(本地依赖)
    手把手教你创建「人物角色Persona」
    微服务与Docker介绍
    深入学习微框架:Spring Boot
    技术干货:我们的项目是如何技术选型的
    为什么选择Spring Boot作为微服务的入门级微框架
    Android Material Design 兼容库的使用详解
    Android 实现QQ、微信、新浪微博和百度第三方登录
    Android ijkplayer详解使用教程
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4068740.html
Copyright © 2020-2023  润新知