Can I get all the benefits of garbage collection using C++ constructors and destructors?
Carefully designed C++ constructors(2) and destructors(2) can go a long way towards easing the pain of manual memory management. Objects can know how to deallocate all their associated resources, including dependent objects (by recursive destruction). This means that clients of a class library do not need to worry about how to free resources allocated on their behalf. Unfortunately, they still need to worry about when to free such resources. Unless all objects are allocated for precisely one purpose, and referred to from just one place (or from within one compound data structure that will be destroyed atomically), then a piece of code that has finished with an object cannot determine that it is safe to call the destructor; it cannot be certain (especially when working with other people’s code) that there is not another piece of code that will try to use the object subsequently. This is where garbage collection has the advantage, because it can determine when a given object is no longer