effective C++学习(Resource Management)

Resource Management

Item 13: Use objects to manage resources.

1.     We should use objects to manageresources to ensure that these resources are released when they are usedanymore.

2.     Using the std::auto_ptr tomanage resources, only allow a small pointer to appoint these resources. Theirassignment operator and copy constructor is not the same as others.

   std::auto_ptr<Investment>pInv1(createInvestment());

      

   std::auto_ptr<Investment> pInv2(pInv1);

//pInv2would point the resources and the pInv1 was assigned //null

   pInv1 = pInv2;

       //the assignment operator is the same ascopy constructor.

3.     The std::tr1::shared_ptr,different from the std::auto_ptr, allow multi pointers to point the sameresources and count the number of references, so it is also namedreference-counting smart pointer(RCSP). When no pointer points the resources,they will be released. However, RCSPs can’t break out cycles of references. Theassignment operator and copy constructor of shared_ptr is normal, so it can beused by STL container and other places where auto_ptr can’t be used.

4.     Both shared_ptr and auto_ptrcan’t release the array resources due to the delete is used but not delete[] in their destructors.

   std::auto_ptr<std::string> aps(new std::string[10]); //error!

   std::tr1::shared_ptr<int> api(new int[1024]);    //error!

       Note:This way can pass the compiler.

5.     Resource Acquisition IsInitialization(RAII): 资源取得的时机就是初始化时机。

Item 14: Think carefully about copying behavior inresource-managing classes.

1.     The following two methodsdealing with this situation:

1)     Forbid to copy, make the copyconstructors private or derive the classes whose copy constructors are private.

2)     Reference-count. When the countis 0, delete the objects. However, if we use the shared_ptr, as to Mutex, whenthe count is 0, we need to unlock but not delete. Fortunately, shared_ptrallows users to use user-defined delete-function.

class Lock

{

public:

  explicitLock(Mutex* pm)

     : mutexPtr(pm, unlock)

  {

     lock(mutexPtr.get()); 

  }

private:

  std::tr1::shared_ptr<Mutex> mutexPtr;

};

Note: the unlock is defined by user.

2.     Copy resource-manage classescan be yet achieved by the following two points:

1)     Deep copying, if the resourcescan be copied, you can copy their resources copying the resource-manageclasses.

2)     Transfer ownership ofresources. It is to ensure only one to manage the resources, such as auto_ptr.

Item 15: Provide access to raw(生的,未加工的,原始的) resources in resource-managing classes.

1.     Many APIs directly require theraw resources when used. It, therefore, is necessary for RAII classes to provideaccess to raw resources. We have two ways, explicit conversion and implicitconversion, to reach the goal.

typedef unsigned long int FontHandle;

void releaseFont(FontHandle hf){hf=0;}

FontHandlegetFont(){return rand();}

class Font

{

public:

   explicitFont(FontHandle fh)

      : f(fh)

   {}

   FontHandle get() const{return f;} //explicit conversion

   operatorFontHandle() const{returnf;}//implicit conversion

   ~Font(){releaseFont(f);}

private:

   FontHandle f;

};

int main()

{

   Font font1(getFont());

 

   Font font2(font1);

 

   FontHandle f = font1;

return 0;

}

2.     The explicit conversion may besafer but doesn’t bring a good user experience. On the contrary, the implicitconversion can be used more conveniently but may increase the errors. Forinstance, the red words, in the code above, bring the errors we don’t except.We wanted to declare a Font, but we mistakenly declare a FontHandle variable.The compiler does not also point out the mistake due to implicit conversion.

Item 16: Use the same form in corresponding uses of newand delete.

1.     If you use “new []”, you mustuse “delete []”, and if you use ”new”, you must use ”delete”.

2.     The “new” and “delete” bringevents:

“new”: allocate memory à call constructors

“delete”: call destructors à release memory

3.     We had better not use “typedefs”for array because of the fact:

typedef std::string AddressLines[4];

std::string*pal = new AddressLines;

 

delete pal;//error!

delete [] pal;//good!

              Note:Where the “AddressLines” is an array, obviously, it is not a good way.

Item 17: Store newed objects in smart pointers instandalone(独立的) statements.

1.     Firstly, what we need to knowis that C++ can freely adjust the order of all operators in a statement, so weshould store newed objects in smart pointers in standalone statements to ensurethe smart pointers have stored the newed objects. E.g.

processWidget(std::tr1::shared_ptr<Widget>(newWidget), priority());

       Note:before the processWidget is called, the compiler must do these three operators:

1)     Call priority();

2)     Execute “new Widget”;

3)     Call the constructor oftr1::shared_ptr;

If the order is changed into this:

1)     Execute “new Widget”;

2)     Call priority();

3)     Call the constructor oftr1:shared_ptr;

Of course the “newWidget” must be in front of the “tr1::shared_ptr”. Now let us consider thissituation:

If thepriority() throw an exception, the resources in Widget would not be stored in thesmart pointers. Resource leaks will occur.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值