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

jon*_*ong 5 delphi variables destructor memory-leaks class

在类变量中使用动态数组来存储在调用类析构函数时需要释放的对象不起作用.

在调用类析构函数之前,数组似乎已经超出了范围并且已经被处理掉了.这是设计的吗?

在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;
Run Code Online (Sandbox Code Playgroud)

who*_*ddy 5

类析构函数被称为AFTER单元终结,因此这意味着在调用类析构函数时,Array不再存在.在单元最终确定时,RTL会清除所有管理变量.最后它应该没关系,因为它实际上不是泄漏.

艾伦·鲍尔提供有关类构造函数/析构函数一些更多的信息在这里.

编辑

显然这是设计的