How do i return an object from a function in Delphi without causing Access Violation?

后端 未结 10 1239
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 14:54

I have a delphi function that returns a TStringList, but when I return a value and try to use it I get a Access Violation Error i.e

myStringList := FuncStringLis         


        
10条回答
  •  逝去的感伤
    2021-02-13 15:27

    As Smasher said, you can't free it; the code calling the function that returns the object is responsible for destroying it.

    This is bad code design, by the way, as it makes it confusing as to who allocates and frees. A much better way to do it would be to have the caller create the object and pass it in to the function. That way, the code that creates it also frees it. Something like this:

    var
      SL: TStringList;
    begin
      SL := TStringList.Create;
      try
        ProcToFillStringList(SL);
        //Do something with populated list
      finally
        SL.Free;
      end;
    end;
    
    // Note I've made the parameter a TStrings and not a TStringList. This allows
    // passing a TMemo.Lines or a TListBox or TComboBox Items as well.
    procedure ProcToFillStringList(const SList: TStrings);
      // Do whatever populates the list with SList.Add()
    end;
    

    Now there's no confusion over who does what - the same code that creates the object is responsible for freeing it. And the code, IMO, is much clearer to read and maintain.

提交回复
热议问题