effective c++ 条款13 use object to manage resources.

请求的系统资源需要最终还回系统,为了避免遗忘返还这个动作,可以利用析构函数在object销毁时自动调用的特点来实现。

简单说就是用object来管理资源。

以内存资源为例

class Investment {}; 

Investment* creatInvestment(){...} // factory function to produce investment object

void main()
{
  Investment* pInv = creatInvestment();//call to get investment object
  
  ....
  
  delete pInv;           // sometime we forget this, happens   
}

//solution
void main()
{
   stid::auto_ptr<Investment> pInv(creatInvestment());
   
   ...
}//when pInv is destroied, auto_ptr will be released.

//problem with auto_ptr
//only one auto_ptr can point to one object
//if auto_ptr was assgined to another auto_ptr
//original auto_ptr would be null
//see following example:
void main()
{
   stid::auto_ptr<Investment> pInv1(creatInvestment());
   
    stid::auto_ptr<Investment> pInv2(pInv1); //pInv1 null
    
    pInv1 = pInv2;//pInv2 null
   ...
}

所以使用auto_ptr 在赋值或者复制时会产生问题。我们并不希望赋值以后就把原来的指针变成null

替代方案是使用  

void main()
{
   stid::shared_ptr<Investment> pInv1(creatInvestment());
   
    stid::shared_ptr<Investment> pInv2(pInv1); //pInv1 null
    
    pInv1 = pInv2;//pInv2 null
   ...
}

在拷贝时完全不会发生问题。需要注意的是在auto_ptr, shared_ptr中使用的是delete 而不是delete[]

如果我们

 stid::shared_ptr<Investment> pInv1(new char[10]);
会产生问题。

 

 

转载于:https://www.cnblogs.com/williamwood/p/3830745.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值