我有以下 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 是否已分配。如果我放弃异常处理,我的应用程序将抛出错误。 Allocations 是一个 TObjectList,如果它是一个数组 - 我会怀疑我没有为数组分配长度,但它是一个 TObjectList。
非常感谢!
最佳答案
TObjectList
通常负责销毁其内容。在这种情况下不要释放您的对象。这将导致释放 TObjectList
时发生访问冲突,因为它会尝试再次释放所包含的对象。
对象列表的这种行为可以在其构造函数中控制:
constructor TObjectList.Create(AOwnsObjects: Boolean);
使用此选项指定您是否希望列表拥有其内容(意味着:当项目从列表中删除或列表被销毁时,它会负责销毁该项目)。不带参数的构造函数(您可能使用过)将其设置为 true
。
您可能只需要一个像 TList
这样的列表,但用于存储对象。如果是这种情况,请像这样创建您的列表:
Allocations:= TObjectList.Create(False);
但是如果您想要自动销毁行为,那么只需删除 for 循环即可。对象列表将销毁您的 TXX_ALOC
对象。
关于delphi - 释放 TObjectList 时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7079133/