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]);
会产生问题。

 

 

posted @ 2014-07-08 02:45  williamwood  阅读(151)  评论(0编辑  收藏  举报