加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 09:30:17 所属栏目:大数据 来源:网络整理
导读:在类变量中使用动态数组来存储在调用类析构函数时需要释放的对象不起作用. 在调用类析构函数之前,数组似乎已经超出了范围并且已经被处理掉了. 这是设计的吗? 在XE5中测试的示例: type TLeakingObject = class public I : Integer; end; TTheLeakOwner = cl
在类变量中使用动态数组来存储在调用类析构函数时需要释放的对象不起作用.

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

在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;

解决方法

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

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

编辑

显然这是在design之前

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读