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