Bug? GC collects memory that references itself.

Stewart Gordon smjg_1998 at yahoo.com
Thu Oct 29 15:02:39 PDT 2009

Jeremie Pelletier wrote:
> Simen Kjaeraas wrote:
>> Jeremie Pelletier <jeremiep at gmail.com> wrote:
>>> I need objects that may live without any references in GC memory, 
>>> this is for bindings to a C++ library. Using ranges or roots would be 
>>> very inneficient so my solution was to have the objects reference 
>>> themselves until the C++ side of the object calls a finalizer which 
>>> nullify the reference to let the GC collect the memory.
>>> The GC doesn't see things this way however, and collects the objects 
>>> even when they reference themselves.

Correct.  For a GC-allocated object to remain alive, it must be 
reachable, i.e. there must exist a chain of references that leads to it 
from at least one of:
- each thread's stack
- the static data segment
- the list of roots added using std.gc.addRoot or std.gc.addRange.

The existence of some reference of it somewhere in the heap is not 
sufficient.  If it were, the GC would be very slow, since it would have 
to either
- scan every bit of heap-allocated memory, not just what is reachable
- use reference counting, itself a performance hit

> It would be too slow for the GC to manage hundreds or thousands of roots.

Really?  Have you experimented?

> I think I'm just going to use an array of pointers and let the objects 
> know their index in that array, it seems to be the fastest solution with 
> the GC.

Certainly one way to do it, though I'm a little confused about why 
adding GC roots would be any slower than this.

> The D class tree for the C++ interface can be subclassed so they 
> will most likely contain references to D memory.

If that's the case, there will likely be a number of GC nodes for each 
of your special objects, and so an extra one surely isn't going to add 
up to much.


More information about the Digitalmars-d-learn mailing list