微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个参数作为对象的方法(下面的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中创建的对象?

解决方法

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

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

你要么必须在doSomething()中释放它(这是我不建议做的练习):

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

或者,您需要在test()中创建一个额外的变量,将其传递给doSomething(),然后在doSomething()返回后释放它:

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在StackOverflow答案中证实了这一点:

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

原文地址:https://www.jb51.cc/delphi/239258.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐