Reflections on Garbage Collection

Many C/C++ programmers think of automatic garbage collection as the

Holy Grail of programming languages; one that will free them from every

conceivable bug. This approach is wrong, though. A garbage collector

can't handle every resource that might leak.

A typical garbage collector takes care of recycling unreferenced

memory. In certain programming languages, it can reclaim leaked threads

and even close open files. However, many other platform- and

application-specific resources still need to be released explicitly by

the programmer.

Think of a modem. An application that uses it must release it

explicitly so that other applications can use it; how many garbage

collectors are modem-aware? Take a database lock, for example. Here

again, you can't expect a garbage collector to close an unused database

lock automatically. Indeed, most RDBM systems set a timeout limit on

each transaction but relying on timeouts instead of closing a lock as

soon as possible results in poor performance and constant deadlocks).

Thus, a garbage collector can be useful as long as it takes care of

reclaiming unreferenced memory. When it comes to reclaiming other time-

critical or scarce system resources, you still need to release them


When you think of dynamically allocated objects as an instance of such

resources, you may realize that garbage collection isn't really that

useful after all. Furthermore, using standard C++, you almost never

need to deal with dynamic memory directly. Instead of using char

arrays, bare pointers and dynamic memory allocation, use string

objects, auto_ptr template, and STL containers. These classes manage

their storage automatically. Note also that, in many cases, you can

create objects on the stack rather than allocate them on the heap.

That said, for certain applications (especially ones developed in C),

you could install a free garbage collector such as the Boehm-Demers-

Weiser conservative garbage collector (see Unlike a copying

garbage collector, a conservative garbage collector doesn't move

objects from one memory location to another. It uses constant sized

memory chunks. This way, the heap doesn't become fragmented.

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon