How to free an object from within one of its own methods?

delphi, memory-management, object

Solution

If the very last act of `ProcessAndDone` is to call `Destroy`, or `Free`, then it is fine. If `ProcessAndDone` calls methods, or refers to members, after it has been destroyed, then it's no good. And of course, you'd need to put a `try/finally` inside `ProcessAndDone` to make sure the destruction happens.

But all that said, you should not do this. Patterns exist for clarity, and for the benefit of other readers. Whenever we see

obj := TMyObject.Create;

we also expect to see a `try/finally` block with a call to `Free`. Don't go against the grain.

Problem

Is there a way to safely free an object from within one of its own methods? (I don't need to nil the objects variable) ``` var Msg: TAMessage; begin Msg := TAMessage.Create(); Msg.ProcessAndDone; end; ``` And I want `TAMessage.ProcessAndDone()` method to destroy the object itself (in the above case `Msg`) because I won't need the object after calling `ProcessAndDone` method, and I don't want to call `Free` or `Destroy` each time right after I call `ProcessAndDone` (for the sake of code clarity). I know setting a TThread's `FreeOnTerminate` property does this but the actual freeing process is handled by a wrapper called ThreadProc which calls thread's `Execute` within.

Original source