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

后端 未结 10 1242
被撕碎了的回忆
被撕碎了的回忆 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:31

    A policy I have with such situations is to pass the stringlist content through the text property and just pass the string returned to the function. This way there's no need to discuss who release who. Of course, you have to do a little more coding, but it's safer. The example is an adaptation of the Ken White's one :

    var
      SL: TStringList;
      Aux: String;
    begin
      SL := TStringList.Create;
      try
        SL.Text := ProcToFillStringList;
        //Do something with populated list
      finally
        SL.Free;
      end;
    end;
    
     // It receives a default param, in the case you have to deal with 
     // StringList with some previous content    
     function ProcToFillStringList(SListContent: String = ''):String;
     // Do the stuff you need to do with the content
    end;
    

    An exception is when all you have is the object and there's no way to retrieve the content on it through a safe type (in this case, strings); then I follow Ken White's idea.

提交回复
热议问题