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:
- 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).
- Resource-managing objects use their destructors to ensure that resources are released.
You can use
std::tr1::shared_ptrto manage heap memory.
There are several points you should keep in mind when you using those two smart pointers:
- std::auto_ptr assumes sole ownership which means copying one to another will set the previous one to null!
- STL containers require that their contents exhibit “normal” copying behavior, so containers of
std::tr1::shared_ptruse 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.