Delphi and finalization in a unit

pKarelian picture pKarelian · Feb 20, 2010 · Viewed 15.3k times · Source

I have two units unitA and unitB. Class TFoo is declared in unitB.

Is it allways safe to call B.Free in finalization of unitA?

How does it depend on in which order unitA and unitB are in dpr?

Can I be sure that unitB exists when unitA finalization is executed?

unit unitB;
interface
type
 TFoo = class
   // code...
  end;
 // code....
end;

unit unitA;
// code..
implementation
uses
 unitB;
var
 A: TStringList;
 B: UnitB.TFoo;

initialization
 A:= TStringList.Create;
 B:= UnitB.TFoo.Create;
finalization
 A.Free;
 B.Free;  // Is it safe to call?
end.

Answer

Jim McKeeth picture Jim McKeeth · Feb 20, 2010

Yes, you should be fine since B is created in Unit A. The rule is that the Initialization sections are called based on the order they are in the DPR, unless one of the units references another unit. In that case, the referenced unit is initialized first. Finalization is in the reverse order.

In your case Unit B does not have an initialization section, so it is a moot point. It will however use the TFoo definition in Unit B when the Unit A initialization section is executed.

Another word of warning about Initialization and Finalization sections - they happen outside of the global exception handler. Any exception that occurs there just terminates the application. So tracking down and debugging those exceptions can be a pain in large programs. You might consider using your own exception logging in there, just to be sure.