Effective C++ Item 13 Use object to manage resources

1. Always use object to manage resource! If you delete a pointer or release a handler manually by yourself, there is great chance that you will make mistake or forget something.

 

2. There are two critical aspects of using object to manage resources:

  2.1 Resources are acquired and immediately turned over to resource-managing objects. The idea of using object to manage resource is often called   Resource Acquisition is Initialization (RAII)

  2.2 Resource-managing objects use their destructors to ensure that resources are released

 

3. You can use std::auto_ptrs or std::tr1::shared_ptr to manage heap memory. And there are several points you should keep in mind when you using those two smart pointers.

  3.1 std::auto_ptrs assumes solo ownership which means copying one to another will set the privious one to null.

  3.2 STL contains require that their contents exhibit "normal" copying behavior, so containers of std::auto_ptrs are not allowed.

  3.3 Both std::auto_ptrs and std::tr1::shared_ptrs use delete in their destructor, not delete []. So using them to manage dynamic allocated memory is not good idea, though, regrettably, one that will compile.

 

你可能感兴趣的:(effective)