Effective C++ item 13: Use objects to manage resources.

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

There are two critical aspects of using objects to manage resources:

  1. Resources are acquired and immediately turned over to resource-managing objects. The idea of using objects to manage resources is often called Resource Acquisition Is Initialization (RAII).
  2. Resource-managing objects use their destructors to ensure that resources are released.
    You can use std::auto_ptrs or std::tr1::shared_ptr to manage heap memory.

There are several points you should keep in mind when you using those two smart pointers:

  1. std::auto_ptr assumes sole ownership which means copying one to another will set the previous one to null!
  2. STL containers require that their contents exhibit “normal” copying behavior, so containers of std::auto_ptr aren’t allowed.
  3. Both std::auto_ptr and std::tr1::shared_ptr use delete in their destructors, not delete[ ]. That means that using them with dynamically allocated arrays is a bad idea, though, regrettably, one that will compile.

“Effective C++” Third Edition by Scott Meyers.