How does the GC work?

Daniel Keep daniel.keep.lists at gmail.com
Fri Aug 24 00:04:10 PDT 2007


Bill Baxter wrote:
> It isn't a reference counting garbage collector.  It's a mark-and-sweep
> type.  That means that every so often it goes through the all the memory
>  marks all the things that it finds references to (both on the GC heap
> and on the current stack), and deletes all the rest.  The "every so
> often" part generally means during allocations.  So the next time you
> use the GC to alloc something, it should delete the garbage.

Actually, it should only do a mark & sweep when you ask it to allocate
some memory, and it discovers that it's run out.

> If you want the behavior of destruction as soon as it goes out of scope,
> then you can use a scope class.
> 
> --bb

Of course, this tragically doesn't work with pointers or arrays.  The
idiom I use is thus:

{
    auto a = new int;
    scope(exit) delete a;

    // do stuff with a
}

This will cause a to be deleted at the end of the scope.

	-- Daniel



More information about the Digitalmars-d mailing list