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

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

    How can i return the TStringList and still free it in the local function?

    You can't. If you free it in the local function, you can't use the return value. Result and vStrList point to the same TStringList object in memory. TStringList is a class and

    Result := vStrList
    

    does therefore not copy the string list, but only copies the reference.

    So, instead you should free the string list in the calling context after you're done working with it or pass the string list as a parameter to your function like this

    procedure FuncStringList (StringList : TStringList);
    

    and let the calling code create and free the string list. As pointed out by the other answers, this is the preferable way, since it makes ownership very clear.

提交回复
热议问题