Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unused interface reference is not destroyed

i had another bug in my app caused by careless usage of Delphi interfaces. When i pass an interface to a procedure which ignores that argument, the instance is never freed. See the following simple example:

ITest = interface
    procedure Test;
end;

Tester = class(TInterfacedObject, ITest)
public
    procedure Test;
end;

Base = class
public
    procedure UseTestOrNot(test : ITest); virtual; abstract;
end;

A = class(Base)
public
    procedure UseTestOrNot(test : ITest); override;
end;

B = class(Base)
public
    procedure UseTestOrNot(test : ITest); override;
end;

{ A }

procedure A.UseTestOrNot(test: ITest);
begin
    test.Test();
end;

{ B }

procedure B.UseTestOrNot(test: ITest);
begin
    WriteLn('No test here');
end;

// -------- Test ---------------------------------------
var
    list : TObjectList<Base>;
    x : Base;
    t : ITest;
begin
    ReportMemoryLeaksOnShutdown := true;

    list := TObjectList<Base>.Create;
    list.Add(A.Create);
    list.Add(B.Create);

    // 1 x Tester leak for each B in list:
    for x in list do
        x.UseTestOrNot(Tester.Create);

    // this is ok
    for x in list do
    begin
        t := Tester.Create;
        x.UseTestOrNot(t);
    end;

    list.Free;
end.

Can you please explain what goes wrong with the reference counter? Can you give any best practice/ guideline (like "Never create an interfaced instance inside a function call [if you don't know what happens inside]).

The best solution i can think of for this example is to write a template method in class Base that saves the passed test instance and calls an abstract DoUseTestOrNot method.

EDIT Delphi 2010

like image 698
hansmaad Avatar asked Jan 13 '11 14:01

hansmaad


1 Answers

It is a different manifestation of the bugs here.
I will add this to the QC report.

This does not reproduce in Delphi XE update 1 any more.

--jeroen

like image 162
Jeroen Wiert Pluimers Avatar answered Oct 03 '22 22:10

Jeroen Wiert Pluimers