[fpc-pascal] When does a reference counted object get freed automatically, and when not?
Howard Page-Clark
hdpc at talktalk.net
Sun Aug 11 00:43:45 CEST 2013
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 ==
More information about the fpc-pascal
mailing list