Inspired by the following posts:
- How do i return an object from a function in Delphi without causing Access Violation?
- Destroying TADODataset created in runtime
I wonder, if there is any option to explicitly tell a function that I want a ByVal result instead of ByRef? Is there any simpler approach to transfer an object's ownership from initial caller to a function and then back.
Consider a function which creates an object at runtime and then passes the reference to this object in a Result
. After calling such a function, the main code keeps on running and 'forgets' to correctly dispose the object... Voilà, a memory leak. This would also look weird if main code frees an object created by another function.
On the other hand, if the object is freed inside the function, then the reference also gets destroyed and this leads to AV.
Why not just declare a 'dummy' (uninitialized) object in the main code and inizialize a dummy object with a function result? Then the only thing I must take care of -- is to free a dummy object in my Form's OnDestroy
. The function's code can be moved to a separate unit where all creation/destruction stuff will be taken care of by initialization
/finalization
blocks or AfterCreation
/BeforeDestruction
events.
The only thing I need -- is to make sure my function returns a ByVal result instead of ByRef. So the result (object) is merely copied to a dummy object and then gets freed inside a function.
IMO this could be much easier to manage and to read than passing a dummy object or TComponent owner to function as a parameter.