Delphi: how to create a free object created dynamically as a method parameter

I have a method with a parameter as an object (sniper code below):

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; 

How to destroy an object created inside a called doSomething method outside this method?

+5
source share
1 answer

To free an instance of an object, you need to have a link to it, which you can call Free() .

Since you instantiate the object in place as a parameter, the only reference you'll have is the inside of the doSomething() parameter.

Do you either have Free inside doSomething() (this is a practice that I would not recommend):

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

Or you need to create an additional variable in test() , pass it to doSomething() , and then Free after doSomething() :

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

Although you might think that using a reference counting object will allow you to create an object in place and allow the reference count to free the object, such a construction may not work due to the following problem with the compiler:

The compiler must store a hidden link when passing just created object instances directly as const interface parameters

This is confirmed by former Embarcadero compiler engineer Barry Kelly in StackOverflow's answer:

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

+8
source

All Articles