The collector and collectable objects must cooperate with each other by abiding to a simple protocol:
class GC { public: virtual GCObject * trace (GCObject *) = 0; inline void trace (GCObject& obj); };
Briefly, the rules are as follows:
void Foo::trace(GC * gc) { ... }
p
to a collectable object of type Bar, then add:
p = (Bar)gc->trace(p);to the body of
Foo::trace
.
x
that is a subclass of GCObject, also add:
gc->trace(x);to the body of
Foo::trace
.
Bar
that
is a subclass of GCObject, add:
Bar::trace(gc);to the body of
Foo::trace
.
This protocol can be used by both copying and non-copying collectors. In addition, the class GCVerifier also uses this protocol to walk the heap in order to verify the integrity of a garbage collected data structure.