Make sure you are doing RAII properly

| 0 Comments

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 ;)

Leave a comment