GC: Yeah, everybody "knows" how it works. How does it?

dsimcha dsimcha at yahoo.com
Thu May 7 09:57:38 PDT 2009


== Quote from Leandro Lucarella (llucax at gmail.com)'s article
> (from the bottom up, in chronological order, of course)
> If you want to know why you don't have ordering guarantees, it's because
> when the "garbage" is swept, you don't do it by following the connectivity
> graph (as you do when you mark the memory). You can't do it even if you
> want to, because you don't have roots to the garbage (that's why it's
> garbage in the first place =). And if you can manage to follow the "old"
> connectivity graph for some magical reason, you still have problems with
> cycles. What if eve have a reference to adam too? What do you destroy
> first? Huston, we have a problem =)

True, but I wish the GC would allow referencing subobjects for the following very
important but very restricted case, just to get around false pointer issues.  It
seems to work in practice anyhow, so all that would have to happen is for it to be
"officially" sanctioned, so that it's not labeled as undefined behavior and thus
arbitrarily dangerous:

1.  You're only referencing sub-objects to explicitly delete them.
2.  These sub-objects are guaranteed to have no more real references and *should*
be freed, but may have false pointers.  If they're large enough, they will have
false pointers with high probability.
3.  These sub-objects contain no finalizers of their own, so the finalizer can't
get run twice.  Calling delete just frees memory.

Example:

class Foo {
    // hugeArray either never escapes or we assume that the lifetime
    // of any escapes is less than the lifetime of the class instance.
    uint[] hugeArray;

    this() {
        hugeArray = new uint[50_000_000];
    }

    ~this() {
        // There are no more real references to hugeArray, since
        // it never escapes this class instance, but it is likely
        // to have false references because it's so huge.
        // Tell the GC that it is ok to delete it anyhow.
        delete hugeArray;
    }
}



More information about the Digitalmars-d mailing list