Note that there are some explanatory texts on larger screens.

plurals
  1. POUnused interface reference is not destroyed
    primarykey
    data
    text
    <p>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:</p> <pre><code>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&lt;Base&gt;; x : Base; t : ITest; begin ReportMemoryLeaksOnShutdown := true; list := TObjectList&lt;Base&gt;.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. </code></pre> <p>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]).</p> <p>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 <code>DoUseTestOrNot</code> method.</p> <p><strong>EDIT</strong> Delphi 2010</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload