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

后端 未结 8 2048
旧巷少年郎
旧巷少年郎 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条回答
  •  梦毁少年i
    2021-01-06 21:44

    No, it is not "memory safe". When you create an object, someone has to free it.

    Your first example leaks memory:

    SL:=TStringList.Create;
    SL.Assign(GetStringList);   // <-- The return value of GetStringList is 
                                //     used, but not freed.
    for i:=0 to 3 do ShowMessage(SL[i]);
    SL.Free;
    

    The second example works fine, but you don't have to create and free an additional temporary instance (Names)

    In general, the second example is slightly better, because it is obvious, who is responsible for the creation and destruction of the list. (The caller) In other situations, a returned object must be freed by the caller or perhaps it's forbidden. You can't tell from the code. If you must do so, it's good practice to name your methods accordingly. (CreateList is better than GetList).

提交回复
热议问题