在类变量中使用动态数组来存储需要在类析构函数被调用时释放的对象是行不通的。
在类析构函数被调用前,该数组似乎已超出其作用域并且已经被处理掉。
这是设计上的问题吗?
在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;