我有一个参数作为对象的方法(下面的sniped代码):
TMyObject=class(TObject)
constructor Create();
destructor Destroy();override;
end;
implementation
function doSomething(x:TMyObject):integer;
begin
//code
end;
procedure test();
var
w:integer;
begin
w:=doSomething(TMyObject.Create);
//here: how to free the created object in line above?
end;
如何在此方法之外的被调用方法 doSomething 内部创建对象?
答案 0 :(得分:9)
为了释放对象实例,您需要引用它,您可以在其上调用Free()
。
由于您是作为参数就地创建对象实例,因此您将拥有的唯一参考是doSomething()
参数内的参考。
您必须在Free
内doSomething()
(这是我不建议做的练习):
function doSomething(x: TMyObject): Integer;
begin
try
//code
finally
x.Free;
end;
end;
或者,您需要在test()
中创建一个额外的变量,将其传递给doSomething()
,然后在Free
返回后将其doSomething()
传递:
procedure test();
var
w: Integer;
o: TMyObject
begin
o := TMyObject.Create;
try
w := doSomething(o);
finally
o.Free;
end;
end;
虽然有人可能认为使用引用计数对象将允许您就地创建对象并让引用计数释放对象,但由于以下编译器问题,这种构造可能不起作用:
前Embarcadero编译工程师Barry Kelly在StackOverflow答案中证实了这一点:
Should the compiler hint/warn when passing object instances directly as const interface parameters?