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

后端 未结 10 1236
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  梦毁少年i
    2021-02-13 15:21

    Simple answer (with examples):

    When you do

    Result := vStrList

    you assign vStrList to Result. At this moment vStrList and Result ARE THE SAME THING! So, in the next line of code, when you free vStrList, you free also Result (well, this is not TECHNICALLY accurate but I used it to keep the explanation simple). This is why you get an AV when you try to use the result of the function. The Result was destroyed when you freed vStrList.

    So, this will solve your problem:

    function FuncStringList:TStringList;
    begin
      Result := TStringList.Create;
      // Do stuff with Result
      // never free (here, in this function) the Result
    end;
    

    The caller of FuncStringList will HAVE TO free "Result".

    You call it like this:

    myStringList := FuncStringList;
    try 
      myStringList.Items.Count                      
    finally
      FreeAndNil(myStringList);    <------------- NOW you can free "Result"
    end;
    

    .

    Another example:

    function makelist: tstringlist;
    begin
      result := Tstringlist.create;
      result.add('1');
      result.add('2');
    end;
    
    procedure TForm1.Button_GOOD_Click(Sender: TObject);
    var list : tstringlist;
    begin
      list := makelist;
      DoStuff(list);
      list.free;      //ok
    end;
    
    procedure TForm1.Button_BAD_Click(Sender: TObject);
    begin
      listbox1.items.Assign(makelist);  // <---- memory leak here because you forgot to free
    end; 
    

    I put this note here before anyone will start 'picking' on my explanation. I used some 'shortcuts' in my explanation in order to avoid complex concepts (such as pointer assignment) keep things very simple. @gath asked a basic question which means that he is still learning the basics of programming.

提交回复
热议问题