Delphi:为什么这会产生内存泄漏?

1 delphi memory-leaks

为什么 TDemo.TBuilder 不会自动释放并产生内存泄漏?TDemo.TBuilder 应该自动释放,因为这是一个基于 IInterface 的 TInterfacedObject 对象

type
  TDemo = class
    public type
      TBuilder = class(TInterfacedObject)
        public
          function Generate: TDemo;
      end;
    public
      class procedure Using;
  end;

implementation

function TDemo.TBuilder.Generate: TDemo;
begin
  Result := TDemo.Create;
  // on finish this method, TDemo.TBuilder should be freed ! 
end;

class procedure TDemo.Using;
begin
  with TDemo.TBuilder.Create.Generate do try
    // use TDemo
    
  finally
    Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

Dal*_*kar 6

您有内存泄漏,因为TBuilder.Create返回对象引用并且因为它在 with call 中用作中间引用,所以它从未分配给接口引用,并且它的引用计数机制从未正确初始化。

为了解决这个问题,您需要声明IBuilder接口并使用返回该接口的类函数来构造这样的中间对象。

  TDemo = class
  public type
    IBuilder = interface
      function Generate: TDemo;
    end;

    TBuilder = class(TInterfacedObject, IBuilder)
    public
      function Generate: TDemo;
      class function New: IBuilder;
    end;
  public
    class procedure Using;
  end;


class function TDemo.TBuilder.New: IBuilder;
begin
  Result := TBuilder.Create;
end;

  with TDemo.TBuilder.New.Generate do
  ... 
Run Code Online (Sandbox Code Playgroud)