Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi destructors: executing code after inherited call?

is it really okay in Delphi to execute code after the inherited call in a destructor?

You can find this in System.Classes:

destructor TThread.Destroy;
begin
[...]
  inherited Destroy;
  FFatalException.Free;
end;

I think, that accessing an instance member after calling the inherited Destroy method is a bad idea.

like image 320
TmTron Avatar asked Jun 25 '13 11:06

TmTron


2 Answers

It is perfectly safe to execute code after a call to an inherited destructor, so long as that code does not rely on something that has been destroyed by that inherited destructor. In the same way it is safe to execute code before a call to an inherited constructor, so long as the code does not rely on anything instantiated in that inherited constructor.

But it is certainly true that this is not good style. There are on occasions reasons that would lead you to such code, but usually such reasons should be taken as indication that something is wrong in your design.

In the example that you give there is simply no need to write the code that way. The call to FFatalException.Free could perfectly well happen before the call to the inherited destructor.

like image 86
David Heffernan Avatar answered Nov 15 '22 17:11

David Heffernan


The instance is not removed from memory by the destructor method itself but by the call of TObject.FreeInstance

TObject.FreeInstance is called, because a destructor is called, after processing the destructor code.

BTW: It is the same to the constructor. The instance is created by class function TObject.NewInstance : TObject and it is called before the constructor is called (just because it is a constructor)

Because of this, you will have a valid instance inside the whole constructor or destructor code.

like image 21
Sir Rufo Avatar answered Nov 15 '22 17:11

Sir Rufo