gpt4 book ai didi

Delphi 类变量在调用类析构函数之前超出范围

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

在类变量中使用动态数组来存储调用类析构函数时需要释放的对象是行不通的。

该数组似乎超出了范围,并且在调用类析构函数之前已被释放。这是设计使然吗?

在 XE5 中测试的示例:

type
TLeakingObject = class
public
I : Integer;
end;

TTheLeakOwner = class
public
class var OutofScopeArray:array of TLeakingObject;
procedure Add;
class destructor Destroy;
end;

procedure TestThis;
var LeakingTest : TTheLeakOwner;
begin
LeakingTest := TTheLeakOwner.Create;
try
LeakingTest.Add;
finally
LeakingTest.DisposeOf;
end;
end;

{ TTheLeakOwner }

procedure TTheLeakOwner.Add;
begin
setlength(OutofScopeArray, length(OutofScopeArray) + 1);
OutofScopeArray[length(OutofScopeArray) - 1] := TLeakingObject.Create;
end;

class destructor TTheLeakOwner.Destroy;
var I: Integer;
begin
// Length(OutofScopeArray) always = 0, gone out of scope before class destructor ??
for I := 0 to Length(OutofScopeArray) - 1 do
FreeAndNil(OutofScopeArray[i]);
end;

最佳答案

类析构函数在单元终结后调用,因此这意味着在调用类析构函数时数组不再存在。在单元完成时,所有托管变量都由 RTL 清除。最终这应该不重要,因为它并不是真正的泄漏。

Allen Bauer 提供了有关类构造函数/析构函数的更多信息 here .

编辑

显然这是 design 的作者

关于Delphi 类变量在调用类析构函数之前超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332847/

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