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

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

    Simple answer: you can't. Why are you trying to? Is it because you've learned that you need to free every object you create in the same function in which they're created? That's generally correct, but not always, and this is one of the exceptions to the rule. A better way to put it is that every object must be freed by its owner.

    If you have a function that generates an object, like this one, but then passes it on to another function, it doesn't take ownership of the object. Remove the call to free and document it, so you (and anyone else who uses this function) will realize that it creates a new object that the code that calls it has to take ownership of.

提交回复
热议问题