相关疑难解决方法(0)

为什么基于TComponent泄漏内存的接口实现?

此Delphi代码将显示TMyImplementation实例的内存泄漏:

program LeakTest;

uses
  Classes;

type
  MyInterface = interface
  end;

  TMyImplementation = class(TComponent, MyInterface)
  end;

  TMyContainer = class(TObject)
  private
    FInt: MyInterface;
  public
    property Impl: MyInterface read FInt write FInt;
  end;

var
  C: TMyContainer;
begin
  ReportMemoryLeaksOnShutdown := True;

  C := TMyContainer.Create;
  C.Impl := TMyImplementation.Create(nil);
  C.Free;
end.
Run Code Online (Sandbox Code Playgroud)

如果TComponent被TInterfacedObject替换并且构造函数更改为Create(),则泄漏消失.与TComponent有什么不同?

非常感谢答案.总结一下:说"如果你使用接口,它们是引用计数,因此它们可以为你释放,这很容易,但却是错误的." - 实际上任何实现接口的类都可以破坏这个规则.(并且不会显示编译器提示或警告.)

delphi memory-leaks interface delphi-2009

18
推荐指数
3
解决办法
2430
查看次数

标签 统计

delphi ×1

delphi-2009 ×1

interface ×1

memory-leaks ×1