【发布时间】:2013-10-20 09:38:48
【问题描述】:
在类变量中使用动态数组来存储调用类析构函数时需要释放的对象是行不通的。
该数组似乎已超出范围并在调用类析构函数之前已被处理掉。 这是设计的吗?
在 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;
【问题讨论】:
-
不是一个答案,而是一些建议:不要对对象使用数组,而是 TObjectList
(generics.collections),当列表超出范围时,它会为您释放对象。 -
是的,我知道,但是这个泄漏发生在一个开源线程池库中,所以我想知道这是否符合语言的预期,然后再在那里闲逛。
-
不用担心,在类析构函数之前清理vars,看我的回答
标签: delphi class variables memory-leaks destructor