Unused interface reference is not destroyed

泪湿孤枕 提交于 2019-12-21 02:29:06

问题


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


回答1:


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




回答2:


Add a guid to you ITest declaration

ITest = interface
['{DB6637F9-FAD3-4765-9EC1-0A374AAC7469}']
    procedure Test;
end;

Change the loop to this

for x in list do
    x.UseTestOrNot(Tester.Create as ITest);

The GUID is neccesary to be able to use as

Test.Create as ITest makes the compiler to add the release where the created object goes out of scope.



来源:https://stackoverflow.com/questions/4681285/unused-interface-reference-is-not-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!