function returning TInterfacedObject
Posted on 2003-10-24
It is convenient, in my code, for me to have a function returning an instance of an object without me having to worry about managing that instance .. in other words, I am looking for garbage collection.
I don't know much about interfaces, but I thought the following might work
function getAsString: String;
property AsString : String read getAsString;
function Tfred.getAsString: String;
result := inttostr(refCount);
Ttom = class
function aFred: Tfred;
end; // Ttom
function Ttom.aFred: Tfred;
// never cleaned up
function myFred:Tfred; begin result:=Tfred.create; end;
procedure TForm1.btnTestReferencecountingClick(Sender: TObject);
var k: integer; tom : TTom;
tom := Ttom.create;
for k:=1 to 100 do begin
Is this a correct usage of TinterfacedObject?
I don't think reference counting is going to come into it, but will all my instances of Tfred be released at the end of the calling procedure??
Also, I don't understand how the cleanup can happen correctly without Delphi maintaining some sort of internal list (in which case there would be a hidden overhead, compared to managing the lifetimes yourself). I understand the reference count is maintained with the object, but somehow - at run time - the app must tell the object that it is no longer in scope ..
enlightenment and code correction sought, please