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

delphi – 释放TObjectList时的访问冲突

发布时间:2020-12-15 09:44:53 所属栏目:大数据 来源:网络整理
导读:我有以下Delphi代码: destructor TXX_XXXX.Destroy;vari: Integer;begin if Assigned(Allocations) then begin for i:=0 to (Allocations.Count - 1) do begin try TXX_ALOC(Allocations.Items[i]).Free; except on Ex:Exception do begin OutputDebugStrin
我有以下Delphi代码:

destructor TXX_XXXX.Destroy;
var
i: Integer;
begin
  if Assigned(Allocations) then
  begin
    for i:=0 to (Allocations.Count - 1) do 
    begin
      try
      TXX_ALOC(Allocations.Items[i]).Free;
      except on Ex:Exception do
      begin
        OutputDebugString(PChar('Exception Error Message '+ Ex.Message));
      end;
      end;
    end;

        // Above code works well - no exception

        try
    FreeAndNil(Allocations); {Exception Here}
    except on E:Exception do
    begin
      OutputDebugString(PChar('Exception in xxxxxxxxx.pas'+E.Message));
    end;
    end;
  end;
  inherited;
end;

Access violation at address 4003AB4 in module ‘Vcl50.bpl’. Read of address 2980BFFC

我知道通常由访问冲突引起的

>释放一些以前被释放的物体
>使用一些对象而无需初始化

但是在我免费之前,我检查了Allocations.如果我放弃异常处理,我的应用程序会抛出一些错误的错误.
分配是一个TObjectList,如果它是一个数组 – 我会怀疑我没有给数组分配一个长度,但它是一个TObjectList.

非常感谢!

解决方法

TObjectList通常负责销毁其内容.在这种情况下,不要释放您的对象.这将在释放TObjectList时导致访问冲突,因为它试图再次释放包含的对象.

可以在其构造函数中控制对象列表的此行为:

constructor TObjectList.Create(AOwnsObjects: Boolean);

使用此选项指定您是否希望列表拥有其内容(意味着:它会在从列表中删除项目时销毁项目或者列表被销毁).没有参数的构造函数(您可能使用过)将其设置为true.

您可能只需要像TList这样的列表,但是用于存储对象.如果是这种情况,那么创建如下列表:

Allocations:= TObjectList.Create(False);

但是如果你想要自动销毁行为,那么只需删除for循环.对象列表将破坏您的TXX_ALOC对象.

(编辑:李大同)

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

    推荐文章
      热点阅读