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 ==
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal

Reply via email to