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

后端 未结 8 2000
旧巷少年郎
旧巷少年郎 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;
    

提交回复
热议问题