【发布时间】:2015-03-05 15:23:03
【问题描述】:
在我们的应用程序框架中,我们有某种实例处理程序类,在恢复时它负责捕获由我们的其他控制器/组件/表单/等创建的实例。
声明如下:
TInstanceHandler = class(TFrameworkClass)
strict private
FInstances : TList<TObject>;
procedure FreeInstances();
protected
procedure Initialize(); override;
procedure Finalize(); override;
public
function Delegate<T : class>(const AInstance : T) : T;
end;
以及实现:
procedure TInstanceHandler.FreeInstances();
var AInstance : TObject;
begin
for AInstance in FInstances do
if(Assigned(AInstance)) then AInstance.Free();
FInstances.Free();
end;
procedure TInstanceHandler.Initialize();
begin
inherited;
FInstances := TList<TObject>.Create();
end;
procedure TInstanceHandler.Finalize();
begin
FreeInstances();
inherited;
end;
function TInstanceHandler.Delegate<T>(const AInstance : T) : T;
begin
FInstances.Add(AInstance);
end;
有时发生的情况是我们的程序员忘记了这个类的存在或他的目的,他们释放了他们的实例。
像这样:
with InstanceHandler.Delegate(TStringList.Create()) do
try
//...
finally
Free();
end;
接下来发生的事情是,当TInstanceHandler 最终确定时,它将尝试再次释放委托的实例,这将导致错误。
我知道为什么Assigned 在这种情况下失败的季节,据我所知,我不能使用FreeAndNil。
所以问题是:如何正确检查引用是否已被释放?
【问题讨论】:
-
你为什么不使用 TObjectList
? -
@whosrdaddy
TObjectList会导致同样的错误,这就是为什么我尝试更改为TList以便我可以检测到应该免费的内容 -
我明白了,无论如何正如大卫所说,在这种情况下没有出路。
-
if(Assigned(AInstance)) then AInstance.Free()应该是AInstance.Free()并且您的 Delegate 方法旨在返回一个值而不是。
标签: delphi delphi-xe2