码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-07-08 12:34:28      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   使用   问题   

请求的系统资源需要最终还回系统,为了避免遗忘返还这个动作,可以利用析构函数在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]);
会产生问题。

 

 

effective c++ 条款13 use object to manage resources.,布布扣,bubuko.com

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

标签:des   style   blog   color   使用   问题   

原文地址:http://www.cnblogs.com/williamwood/p/3830745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!