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? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |