www.digitalmars.com [Home] [Search] [D]

Last update Feb 8, 2003


Garbage Collection

D is a fully garbage collected language. That means that it is never necessary to free memory. Just allocate as needed, and the garbage collector will periodically return all unused memory to the pool of available memory.

C and C++ programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of garbage collection. Experience both with new projects written with garbage collection in mind, and converting existing projects to garbage collection shows that:

Garbage collection is not a panacea. There are some downsides: These constraints are addressed by techniques outlined in Memory Management.

How Garbage Collection Works

To be written...

Interfacing Garbage Collected Objects With Foreign Code

The garbage collector looks for roots in its static data segment, and the stacks and register contents of each thread. If the only root of an object is held outside of this, then the collecter will miss it and free the memory.

To avoid this from happening,

Pointers and the Garbage Collector

The garbage collector's algorithms depend on pointers being pointers and not pointers being not pointers. To that end, the following practices that are not unusual in C should be carefully avoided in D: In fact, avoid using pointers at all as much as possible. D provides features rendering most explicit pointer uses obsolete, such as reference objects, dynamic arrays, and garbage collection. Pointers are provided in order to interface successfully with C API's and for some wizard level work.

Working with the Garbage Collector

Garbage collection doesn't solve every memory deallocation problem. For example, if a root to a large data structure is kept, the garbage collector cannot reclaim it, even if it is never referred to again. To eliminate this problem, it is good practice to set a reference or pointer to an object to null when no longer needed.

This advice applies only to static references or references embedded inside other objects. There is not much point for such stored on the stack to be nulled, since the collector doesn't scan for roots past the top of the stack, and because new stack frames are initialized anyway.


Copyright (c) 1999-2001 by Digital Mars, All Rights Reserved