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?
source share