Is it memory safe to provide an object as a function result?

后端 未结 8 2070
旧巷少年郎
旧巷少年郎 2021-01-06 21:05

Here I provide simple piece of code.

function GetStringList:TStringList;
var i:integer;
begin
   Result:=TStringList.Create;
   Result.Add(\'Adam\');
   Res         


        
8条回答
  •  渐次进展
    2021-01-06 21:48

    I use a combination of both idioms. Pass the object as an optional parameter and if not passed, create the object. And in either case return the object as the function result.

    This technique has (1) the flexibility of the creation of the object inside of the called function, and (2) the caller control of the caller passing the object as a parameter. Control in two meanings: control in the real type of the object being used, and control about the moment when to free the object.

    This simple piece of code exemplifies this idiom.

    function MakeList(aList:TStrings = nil):TStrings;
     var s:TStrings;
     begin
       s:=aList;
       if s=nil then 
         s:=TSTringList.Create;
       s.Add('Adam');
       s.Add('Eva');
       result:=s;
     end;
    

    And here are three different ways to use it

    simplest usage, for quick and dirty code

    var sl1,sl2,sl3:TStrings;
    sl1:=MakeList;
    

    when programmer wants to make more explicit ownership and/or use a custom type

    sl2:=MakeList(TMyStringsList.create);
    

    when the object is previously created

    sl3:=TMyStringList.Create;
    ....
    MakeList(sl3);
    

提交回复
热议问题