0

Basic question. In Button1Click I create an interfaced object. Reference counting after creation is 0. I pass the object as an argument. Ref counting increase, decrease at the end of the function and as it 0, its getting destroyed. Do I miss something? When I create the object in the first place, I was thinking that ref counting should be 1? lListFilter is not holding a reference to the object?

type
    IPersistentListFilter = Interface(IInterface)
        ['{57cdcf89-60ee-4b3c-99fd-177b4b98d7e5}']
        procedure IncludeObject;
end;

procedure FillList(AFilter : IPersistentListFilter);

type
TPersistentListFilter = class(TInterfacedObject, IPersistentListFilter)
    procedure IncludeObject;
    constructor Create;
    destructor Destroy; override;
end;

implementation

procedure FillList(AFilter: IPersistentListFilter);
begin
     AFilter.IncludeObject;
end;

constructor TPersistentListFilter.Create;
begin
    inherited;
end;

destructor TPersistentListFilter.Destroy;
begin
    inherited;
end;

procedure TPersistentListFilter.IncludeObject;
begin
    // do nothing
end;

procedure TForm8.Button1Click(Sender: TObject);
var
    lListFilter: TPersistentListFilter;
begin
    lListFilter := TPersistentListFilter.Create;
    // ref count is 0
    FillList(lListFilter);
    // lListFilter has been destroyed
    FillList(lListFilter);  // --> error
end;
siwmas
  • 389
  • 2
  • 15

1 Answers1

2

In Button1Click, lListFilter is declared as an instance of TPersistentListFilter, not IPersistentListFilter. Thus, no reference counting occurs when lListFilter is created.

lListFilter needs to be declared as IPersistentListFilter:

procedure TForm8.Button1Click(Sender: TObject);
var
  lListFilter: IPersistentListFilter;
begin
  lListFilter := TPersistentListFilter.Create;
  // ref count will be 1

  // ref count will go to 2 during call to FillList
  FillList(lListFilter);

  // ref count will be back to 1

  // ref count will go to 2 during call to FillList
  FillList(lListFilter);  

  // ref count will be back to 1

end;   // ref count will go to 0 as lListFilter goes out of scope 
       //    and is destroyed.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Dave Olson
  • 1,435
  • 1
  • 9
  • 16
  • Thnks Dave! Its clear now why .create did not increased ref count, but im still confused why FillList(lListFilter) did increase the ref count regarding the fact that it has been declared wrongly as TPersistentListFilter.. – siwmas Jun 22 '17 at 10:55
  • 1
    Because `FillList` accepts `IPersistentListFilter` as its argument – David Heffernan Jun 22 '17 at 11:09
  • Because the 'AFilter' parameter to 'FillList' is declared as 'IPersistentListFilter'; 'lListFilter' would be passed *as* 'IPersistentListFilter', not as 'TPersistentListFilter' – Dave Olson Jun 22 '17 at 11:19