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

后端 未结 8 2003
旧巷少年郎
旧巷少年郎 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:51

    It is the usage that is the leak, not the construct itself.

    var sl2 : TStringlist;
    
    sl2:=GetStringList;
    sl.assign(sl2);
    sl2.free;
    

    is perfectly fine, or easier even,

    sl:=getstringlist;
    // no assign, thus no copy, one created one freed.
    sl.free;
    
    0 讨论(0)
  • 2021-01-06 21:58

    In btn1Click you should do:

    var sl2: TStringList;
    
    sl2 := GetStringList:
    SL.Assign(sl2);
    sl2.Free;
    

    In btn2Click you don't have to create an instance of SL before calling ProvideStringList to not create a memory leak.

    0 讨论(0)
提交回复
热议问题