Discussion Topic #3: STL Containers and Object Destruction
Wednesday, June 14, 2006
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.
- 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> >).
- If a container does not own the objects it holds, the use of raw pointers is okay (e.g. vector<foo*>).
- 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.
- 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.
- The copy constructor of your object might be really expensive and therefore raw pointers to those objects might be held in the container.
- 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.
-Gilemonster
Labels: C++
posted by Gilemonster @ 9:10 PM,
2 Comments:
- At 12:58 PM, said...
-
Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program! - At 2:42 PM, Gilemonster said...
-
Never heard of it. Sorry.