A place where programmers can discuss various programming topics and experiences.

Discussion Topic #3: STL Containers and Object Destruction

When using STL containers, be aware that they assume they hold value-like objects. One of the pitfalls with this is that during container destruction it assumes that the objects it holds are being fully destructed as well. If your container holds a collection of raw pointers to user-defined objects, this is not the case. The memory each raw pointer points to is actually not destructed unless you manually delete the raw pointer itself. The STL does not do this for you. To help prevent this type of design flaw, here are a few guidelines to use.

  1. If a container owns the objects it holds, use either full object types (e.g. vector<foo>) or reference-counted smart pointers to those objects (e.g. vector< shared_ptr<foo> >).
  2. If a container does not own the objects it holds, the use of raw pointers is okay (e.g. vector<foo*>).
  3. In general, never use containers of auto_ptr (e.g. vector< auto_ptr<foo> >).

Now these are just guidelines and therefore there are exceptions. Here are a few examples.

  1. You have performance and/or space-critical requirements that make the use of containers of raw pointers more attractive. This is perfectly valid, but always be aware that you are required to manually delete those pointers before destructing your container.
  2. The copy constructor of your object might be really expensive and therefore raw pointers to those objects might be held in the container.
  3. You write have a container object that was written to specifically work with auto_ptr (sounds like suicide, but it might be legitimate).

In general, it is probably better to just use reference-counted smart pointers because you then never have to worry about whether you own the object or not. If you do own it, then your count should drop to zero on container destruction and no memory is leaked. Also, if you don't own the objects in your container, then a reference-counted smart pointer merely increments the reference count and decrements it during container construction and destruction respectively. You therefore do not destruct the objects unless you are the last person using them. For more information on reference-counted smart pointers, take a look at shared_ptr. This is a new STL smart pointer from Boost that can prove to be very useful in certain situations.



posted by Gilemonster @ 9:10 PM, , links to this post