Converting Legacy Code to Resource Management
If you're a seasoned developer, you know painfully well how much time is regularly wasted tracking resource bugs. I don't have to convince you that the little time you and your team spend familiarizing yourselves with the principles of resource management will pay over and over. You can start using this methodology immediately, whether you're starting a new project from scratch or are in the middle of an existing project. The conversion doesn't have to be done all at once. Here are the steps.
First of all, make the basic strong templates available in your project. You can download them from the Relisoft Web site. Then start encapsulating naked pointers one by one. You'll find naked pointers by searching your code for calls to new.
The easiest ones to encapsulate are the temporary pointers that are used within a single procedure. Just replace them with auto_ptrs and remove the (hopefully) matching calls to delete. If a pointer is not deleted within the procedure, but rather is returned from it, replace it with an auto_ptr and call the release method before returning its contents. You'll deal with the calls to release in your second pass. Notice that, even at this early point, your code will gain in robustnessyou'll have removed potential leaks resulting from unexpected returns from the middle of a procedure and from exceptions.
Naked pointers within objects go next. Make sure that they're either encapsulated in separate auto_ptrs or allocated in constructors and deallocated in destructors. Again, if you have to pass the ownership, call the release method. If you have containers that own objects, reimplement them using strong vectors.
Next, find all the calls to release and try to eliminate as many as possible. If release is called in order to return a pointer, make the function return an auto_ptr by value. Of course, the callers will have to be changed too. They'll have to use auto_ptrs to receive the results of such calls.
Repeat this procedure until the only calls to new and release occur within constructors or are parts of direct resource transfers. At that point, you'll be done with memory leaks inside your code. Do the same with other kinds of resources your program uses.
You'll notice how resource management eliminates a lot of complexities related to error and exception handling. Not only will your code become more robust, it will actually become simpler and easier to maintain.
Part 2 of this discussion shows a practical example of the application of the resource management methodology.