Mega Code Archive

 
Categories / Delphi / Functions
 

Need to Return a TStringList (any object) from a Delphi Function

Title: Need to Return a TStringList (any object) from a Delphi Function? I'm 99% sure that 100% of your custom Delphi functions return simple types like integers, string or boolean values. Do you know that a Delphi function can return any object type value, like a string list (TStringList) or a button (TButton)? If you know then I guess you also know that you have to be very careful when calling such a function. If you do not know how to code a Delphi function to return an object or if you do not know why you need to be cautious when using object resulting from functions ... read on figure out :) Who needs to Free the Memory? In Delphi for Win32 every object (manually) created needs to be (manually) freed. It's simple. Do not free the objects you create and your program will leak memory and eventually eat all the memory Windows has (plus a few access violations along the way). Here's a simple function which returns a Delphi object - a TStringList: function GetStringList: TStringList; begin result := TStringList.Create; result.Add('an item') ; end; It does look simple. Note that since the function returns a TStrignList and since the result variable is implicitly declared in every function - "result" is a TStringList variable. What's more important here is that when the function is exited - you have a TStringList object created - not used - in memory. Someone needs to free the object before your application ends. Since you will, in most cases, call functions when you need its result, the GetStringList will be called from another piece of code: var sl : TStringList; begin sl := GetStringList; try ShowMessage(sl[0]) ; // or something like // ListBox1.Items.Assign(sl) ; finally sl.Free; end; end; What's important here is that we have a TStringList type variable ("sl") that receives the result of the GetStringList functions, does something with it, and finally, removes the string list from the memory - thus preventing a memory leak. Therefore a warning: when a function returns an instance of an object - always make sure you (knows who needs to) free the object when no longer needed! Note that the TStringList does not need an owner to be created. For objects that need the owner - the owner is responsible and needs to destroy the object.