Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 737
Brian Hawk Avatar asked Oct 19 '25 08:10

Brian Hawk


1 Answers

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.

like image 112
David Heffernan Avatar answered Oct 21 '25 23:10

David Heffernan