什么时候动态数组会收集垃圾?

awm*_*oss 10 delphi

动态数组是引用计数的,因此编译器会自动释放内存.我的问题是,什么时候发生这种自动释放?它会立即发生,还是在包含程序结束时发生?

这是一个具体的例子

procedure DoStuff;
var data:TBytes;
begin
  data:=GetData; // lets say data now contains 1 Gig of data.
  DoStuffWithData(data);
  // I now want to free up this 1Gig of memory before continuing.
  // Is this call needed, or would the memory be freed in the next line anyway?
  Finalize(data); 

  data:=GetMoreData; // The first array now has no remaining references
  DoStuffWithData(data);
end
Run Code Online (Sandbox Code Playgroud)

对Finalize()的调用是多余的吗?

Rob*_*edy 11

呼叫Finalize并不是多余的.确实,动态数组的引用计数将在下一行递减(因此可能会破坏数组),但这只会分配新的动态数组之后发生.在返回之前GetMoreData,但在赋值发生之前,内存中将有两个动态数组.如果你事先手动销毁第一个,那么你一次只能在内存中有一个数组.

您存储的第二个数组data将作为DoStuff返回被销毁(假设DoStuffWithData不在其他地方存储动态数组引用的副本,增加其引用计数).