gpt4 book ai didi

delphi - 动态数组到底什么时候被垃圾回收?

转载 作者:行者123 更新时间:2023-12-03 14:41:48 25 4
gpt4 key购买 nike

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

这是一个具体的例子

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

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

最佳答案

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

存储在 data 中的第二个数组将在 DoStuff 返回时被销毁(假设 DoStuffWithData 不会)不要在其他地方存储动态数组引用的副本,从而增加其引用计数)。

关于delphi - 动态数组到底什么时候被垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8046216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com