gpt4 book ai didi

delphi - 从类引用构造对象

转载 作者:行者123 更新时间:2023-12-03 15:37:25 26 4
gpt4 key购买 nike

我有一个方法,它构造一个对象,调用一个 Execute 方法,然后释放该对象。对象的类型由传递到方法中的 TClass 后代确定。请注意,我所说的是 Delphi for Win32,而不是 .NET。

编辑:我应该指出这是 Delphi 2006,因为在下面的答案中已指出,在未来的版本中可能不需要 NewInstance 调用。然而,就我而言,这是必需的。因此,我想我的问题的答案(安全吗?CreateForm() 是否有潜在的泄漏)需要基于这是 Delphi 2006

Edit#2:似乎针对 D2007 和 D2009 给出的解决方案实际上适用于 D2006。我一定是从早期版本的 Delphi 中养成了“NewInstance”习惯......

function TPageClassFactory.TryExecute(ScrnClass: TCustomPageClass): boolean;
//TCustomPageClass = class of TCustomPage
var
ScrnObj: TCustomPage; //TCustomPage defines an abstract Execute() method
begin
Result := FALSE; //default
ScrnObj := TCustomPage(ScrnClass.NewInstance); //instantiate
try
ScrnObj.Create(Self); //NB: Create() and Execute() are *virtual* methods
ScrnObj.Execute;
finally
FreeAndNil(ScrnObj);
end;
Result := TRUE;
end;

我想知道这是否安全 - 如果 Create() 引发异常会发生什么?

查看来自 Forms.pas.TApplication.CreateForm() 的类似示例,采用了不同的方法进行异常处理(我删除了下面不相关的部分):

procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
var
Instance: TComponent;
begin
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(Self);
except
TComponent(Reference) := nil;
raise;
end;
end;

在Forms.pas方法中,当Create()方法发生异常时,是否意味着内存泄漏?我的理解是 InstanceClass.NewInstance 分配了内存,因此在这种情况下内存没有被释放/释放/释放?

最佳答案

您应该将创建放在 try finally block 之外。

但更好的解决方案是:

type 
TMyClass = class ()
public
constructor Create(...); virtual;
function Execute: Boolean; virtual;
end;
TMyClassClass = class of TMyClass;


procedure CreateExecute(const AClass: TMyClassClass): Boolean;
var
theclass : TMyClass;
begin
theclass := AClass.Create;
try
Result := theclass.Execute;
finally
theclass.Free;
end;
end;

关于delphi - 从类引用构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/465492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com