Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi and finalization in a unit

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.
like image 752
pKarelian Avatar asked Nov 28 '22 15:11

pKarelian


1 Answers

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.

like image 151
Jim McKeeth Avatar answered Dec 10 '22 23:12

Jim McKeeth