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 usestd::auto_ptrs
orstd::tr1::shared_ptr
to 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::auto_ptr
aren’t allowed. - Both
std::auto_ptr
andstd::tr1::shared_ptr
use delete in their destructors, notdelete[ ]
. That means that using them with dynamically allocated arrays is a bad idea, though, regrettably, one that will compile.