此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.如果将TComponent替换为TInterfacedObject,并且构造函数更改为Create(),则泄漏将消失。这里的TComponent有什么不同?
非常感谢你的回答。总结:说“如果你使用接口,它们是引用计数的,因此它们是为你释放的”--实际上任何实现接口的类都可以打破这个规则,这很容易,但却是错误的。(并且不会显示编译器提示或警告。)
发布于 2010-02-02 16:32:42
一个组件应该由其他东西拥有和销毁,通常是一个表单。在这种情况下,不使用引用计数。如果您将一个组件作为接口引用传递,那么当方法返回时,如果它被销毁了,那将是非常不幸的。
因此,TComponent中的引用计数已被删除。
https://stackoverflow.com/questions/2182612
复制相似问题