Cook Computing

Memory Management

August 30, 2003 Written by Charles Cook

I wasted some time the other day with a C++ memory management issue. I was using a class, call it class X, which took a reference to another class, say class Y, in its constructor. I mistakenly assumed that the constructor would copy the required data from the reference to class Y. Unfortunately that was wrong and the program blew up. It turned out that class X stored the reference to class Y as a member variable, acessing the instance of class Y later on after I had deleted it. So I had to ensure that the lifetime of the instance of class Y encompassed the lifetime of the class X instance, which complicated my code.

Maybe I've been corrupted by working with COM for several years but I think that reference counting with smart pointers is the only maintainable way to manage objects in trad C++. Although garbage collection makes things even easier in .NET and Java, it does make non-memory resource management considerably harder. Which reminds me, what did happen to the Chris Sells project to determine the cost of ref counting in .NET?

UPDATE: Looks like the ref counting project is still making progress, as of a couple of months ago anyway.