It's quite an old bone of contention but, IMHO, there's nothing
intrinsically wrong with returning an object created inside a function and, in some ocassions, it can be quite usefull.
The problem arises because it's easy to "forget" to free/release the returned object, so the usual way to implement such functions is to make them accept a parameter of the desired class and make the funciton create/use it. The election is yours.
A good example of this are the overloaded
FindAllFiles(): one requires you to pass a
TStringList created outside where it returns the list of files, while the other creates internally (and returns) a
TStringList which you can assign to an object reference. That is, they can be used as:
{ As a parameter ... }
AList := TStringList.Create;
try
FindAllFiles(AList, ...);
{Do something with AList}
finally
AList.Free;
end;
{ As the function result }
try
AList := FindAllFiles(...);
{Do something with AList}
finally
AList.Free;
end;
This last form allows you to do, for example:
with FindAllFiles(...) do
try
{Do something with the result}
finally
Free;
end;
As you see, the key is that the object returned by the function should be freed inside the callee, so you have to consider (and not forget!) the call to
FindAllFiles as of it were an "special" contructor. Provided you (and every other user of your code) remember that, there should be no problem, although it's considered good practice (in that case) to provide an overload requiring a parameter of the proper class and using it unless otherwise needed.