C++之智能指针 (一 )

//智能指针是一种类派生出的对象,能够在离开代码块的时候,自动delete掉new出的空间,以防止内存泄露 

/*  
    auto_ptr   :(已经被C++11摒弃)建立所有权概念(ownership) 
	            ownership:对于特定的对象,只有一个智能指针可以拥有它,所以只有拥有对象的智能指针的
				          析构函数会删除该对象。 赋值操作可以转让所有权 

    unique_ptr : 策略上与 auto_ptr 相同,但是unique_ptr	更严格。 
		
    shared_ptr : 跟踪 引用特定对象的智能指针 的个数,赋值时,计数+1,指针过期时,计数-1。 
	             则仅当最后一个指向特定对象的指针过期时,才会调用delete。 



*/
/*
    智能指针的构造函数,被explict修饰,不允许 隐式类型 转换,操作符的两个操作数类型必须匹配。 
     例:
       shared_ptr<double> pd;
	   double * p_reg = new  double;
	   
	   pd = p_reg;                                 // 不允许,不能隐式类型转换                                                
	   pd = shared_ptr<double>(p_reg);             // 允许                                                
	                                                                                 
	   shared_ptr<double> pshared = p_reg;         // 不允许,不能隐式类型转换                                                          
	   shared_ptr<double> pshared(p_reg);          // 允许 
	                                                                          

*/

#include<iostream>
#include<string>
#include<memory>
using namespace std;

class Report{
	private:
		string str;
	public:
		Report(string s):str(s){
			cout<<"Object created"<<endl;
		}
		~Report(){
			cout<<"Object deleted!"<<endl;
		}
		void comment() const {
			cout<<str<<endl;
    	}
};

int main(void){
	
  {
	auto_ptr<Report> pa (new Report("using auto_ptr"));
	pa->comment();
  }

  {
	shared_ptr<Report> ps (new Report("using shared_ptr"));
	ps->comment();
  }

  {
	unique_ptr<Report> pu (new Report("using unique_ptr"));
	pu->comment();
  }
	
	return 0;
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值