Delphi: 如何释放动态创建的对象作为方法的参数

Delphi: How to free object created dynamically as a parameter of method

我有一个参数作为对象的方法(下面的代码):

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 内部创建的对象?

为了释放对象实例,您需要有一个可以对其调用的引用 Free()

由于您是就地创建对象实例作为参数,因此您将拥有的唯一引用是 doSomething() 参数内部的引用。

你要么必须 Free 它在 doSomething() 内(我不建议这样做):

function doSomething(x: TMyObject): Integer;
begin
  try
    //code
  finally
    x.Free;
  end;
end;

或者,您需要在 test() 中创建一个附加变量,将其传递给 doSomething(),然后在 doSomething() returns 之后 Free

procedure test();
var
  w: Integer;
  o: TMyObject
begin
  o := TMyObject.Create;
  try
    w := doSomething(o);
  finally
    o.Free;
  end;
end;

虽然有人可能认为使用引用计数对象可以就地创建对象并让引用计数释放对象,但由于以下编译器问题,这种构造可能无法工作:

The compiler should keep a hidden reference when passing freshly created object instances directly as const interface parameters

前 Embarcadero 编译器工程师 Barry Kelly 在 Whosebug 的回答中证实了这一点:

Should the compiler hint/warn when passing object instances directly as const interface parameters?