Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2013-08

When does a reference counted object get freed automatically, and when not?

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Howard Page-Clark

I've been exploring interfaces a bit, and fail to understand when automatic destruction of an object is precipitated by the compiler, and when not.
Consider the lifetime of the two instances i1 and i2 in the following program. It seems that i2 (called in a method of i1) is freed automatically, but i1 is not.

== code begin ==

program integerInterface;
{$mode objfpc}{$H+}
type
   ISortableInteger = interface
   ['{D38A748E-F889-4A2A-9E3C-5154D493061C}']
     function Compare(anIntf: ISortableInteger): integer;
     procedure SetValue(aValue: int64);
     function GetValue: int64;
     property Value: int64 read GetValue write SetValue;
   end;
   { TSortableInteger }
   TSortableInteger = class(TInterfacedObject, ISortableInteger)
   strict private
     Fint: int64;
     procedure SetValue(aValue: int64);
     function GetValue: int64;
   public
     function Compare(anIntf: ISortableInteger): integer;
     property Value: int64 read GetValue write SetValue;
   end;

{ TSortableInteger }

function TSortableInteger.Compare(anIntf: ISortableInteger): integer;
begin
   if Fint > anIntf.Value then
     Result := 1
   else if Fint = anIntf.Value then
     Result := 0
   else
     Result := -1;
end;
function TSortableInteger.GetValue: int64;
begin
   Result := Fint;
end;
procedure TSortableInteger.SetValue(aValue: int64);
begin
   Fint := aValue;
end;
var i1, i2: TSortableInteger;
begin
   i1 := TSortableInteger.Create;
   i1.Value := 21;
   i2 := TSortableInteger.Create;
   i2.Value := 22;
   WriteLn('i1 (21) compared to i2 (22) is ',i1.Compare(i2));
   i1.Free; // why is this necessary with a reference counted interface?
   ReadLn;
end.

== code end ==

Marco van de Voort
to Howard Page-Clark

In our previous episode, Howard Page-Clark said:

var i1, i2: TSortableInteger;

_INTERFACES_ are refcounted, not classes. And these are class references.

Change it to ISortableInteger, remove the free, and it will work fine probably.