[fpc-devel] Improving Ref Counting

DrDiettrich drdiettrich at compuserve.de
Thu Mar 3 13:00:11 CET 2005

peter green wrote:

> surely this also means
> 1: there has to be rtti for every field in every class so the compiler can
> follow the paths from the class

That's almost required, not only for classes but for all data types that
contain references (pointers) to managed objects.

It's not necessarily RTTI where such information resides, the compiler
(Delphi, at least) already maintains such tables for fields with
reference counted data types. These tables are used in the Initialize
and Finalize procedures of every data structure.

> 2: you can't safely cast between classes and untyped pointers or integers
> (because those refs would be invisible to the gc)

It's a matter of the compiler specific handling of managed objects.
Remember that dynamic strings (AnsiString), arrays etc. and their casts
already have to be handled by the compiler.

You'll encounter no problems with pointers as long as the objects are
kept alive by references which GC recognizes. Consider an AnsiString and
an PChar into the string, then the pointer will become invalid when the
string is moved or destroyed. Likewise a pointer to an object will
become invalid when the object is destroyes. These are situations which
you'll have to consider already, even without GC.

> 3: the GC can't work with pointers to things for every class

GC doesn't have to know about pointer types, it's sufficient to
determine that an object at an address (pointer value) is referenced and
consequently is alive. When such an object has fields with further
references, then GC certainly must know about the data type of the

That's why managed objects usually have a somewhat fixed standard
layout, so that GC can find the class type and layout of the object from
e.g. the VMT pointer. Alternatively managed objects can have an
additional (hidden) reference to the layout information, stored before
the begin of the object. Such a preamble also is used by classic memory
managers, though with different contents, so that the MM can return the
memory to the free memory pool when the object is free'd with e.g.
FreeMem, Dispose or Destroy. At this level GC and traditional MM are not
very different ;-)


More information about the fpc-devel mailing list