在Delphi XE中,以下代码会导致内存泄漏:
procedure TForm1.Button1Click(Sender: TObject);
var P, B: TProc;
begin
B := procedure
begin
end;
P := procedure
begin
B;
end;
end;
运行代码
ReportMemoryLeaksOnShutdown := True;
和内存管理器提示:
21-28 bytes: TForm1.Button1Click$ActRec x 1
最佳答案
这是由于匿名方法的工作方式造成的。匿名方法作为 TInterfacedObject 后代实现,如果同一例程中有多个匿名方法,they end up as two methods of the same object.它使用接口(interface)进行引用计数,因此您最终不会泄漏对象。然而,if an anonymous method references itself, that ends up throwing off the reference count并导致内存泄漏。您在这里看到的情况是由这两件事共同造成的。
关于delphi - 嵌套匿名方法发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6273376/