September 01, 2005

Make sure you are doing RAII properly

There's an interesting post over on the Joel On Software forums about RAII in C++. The original poster's problem is clearly stated in the first line of their question:

When the constructor for CTheClass runs, I want to acquire 3 resources. These 3 resources will be freed in the destructor (that's RAII, right?)

Wrong.

The question goes on to point out that if one of the constructors of one of the resources throws and exception then, because the CTheClass constructor hasn't completed the CTheClass destructor doesn't run and the resources that were successfully allocated aren't released.

This issue is dealt with extensively in Scott Meyers' More Effective C++ (item 10). But the key point is this: do not have more than one bare pointer in a class.

Any class that manages the lifetime of a single bare pointer can be considered a "smart pointer" of sorts. For RAII to work all classes that implement RAII must either be a smart pointer or be a collection of smart pointers. A class which contains multiple bare pointers is not performing RAII; no matter how much you think it is....

I fall into this trap myself sometimes; when I'm not thinking straight. This posting is to help me stop ;)


Share this entry: Email it! | bookmark it! | digg it! | reddit!

Posted by Len at September 1, 2005 11:48 AM | Comments (0) | Categories : Geek Speak
Comments
Post a comment









Remember personal info?




Enter this code in the box below to prove that you're not some kind of automated spam robot...