Delphi allows to access an object instance via object reference and interface reference at the same time. Consider this code:
program RefCounts; {$APPTYPE CONSOLE} uses SysUtils; procedure Test; var Obj: TInterfacedObject; II: IInterface; begin Obj:= TInterfacedObject.Create; Writeln(Obj.RefCount); // 0 II:= Obj; Writeln(Obj.RefCount); // 1 II:= nil; // here Obj is already destroyed and we can't reference it anymore // Writeln(Obj.RefCount); end; begin Test; Readln; end.
Nasty thing is that a reference-counted object is created with zero reference counter and can be destroyed by means of an interface reference. Needless to say that combining object and interface references is bad practice and should be avoided. Unfortunately the reference counting (with zero counters allowed) appeared to be a difficult problem for the compiler too and resulted in compiler bugs even when the code compiled does not use object references (see example here). The bugs were getting fixed with newer Delphi versions but nobody can say which Delphi version is free from them.