首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Delphi:为什么会产生内存泄漏?

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

Stack Overflow用户
提问于 2020-12-09 10:54:19
回答 1查看 185关注 0票数 1

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

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-09 12:24:34

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

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

代码语言:javascript
复制
  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
  ... 
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65215370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档