[fpc-devel] Initialize/Finalize management operators and Default intrinsic

Thorsten Engler thorsten.engler at gmx.net
Wed Apr 13 03:32:55 CEST 2016


Sven Barth wrote:
> In that specific example you would be right, but units are seldomly used
in
> isolation and once both unit1 and unit2 are used in more units it isn't
that
> clear (to the user) anymore which unit is initialized first.

I've always found the rules about this very clear in Delphi (and I assumed
so far it applies to FPC as well):

If your unit depends on another unit being initialized before and finalized
after your unit, then that other unit must be listed in the interface uses
clause.

Units in the implementation uses clause may initialize before or after your
unit, and the order may change in the future depending on the contents of
other units in the project. But all units in the interface section are
guaranteed to have been initialized before your unit and are guaranteed to
finalize after your unit.

So if you depend on another unit being initialized first, list it in the
interface section. If you can't because of circular references, then your
code is broken and what you want to do is impossible.

Delphi ensures this is true, even when dynamically loaded packages come into
play, by essentially creating the following code for each unit behind the
scenes:

Unit ThisUnit;

Interface

Uses
  InterfaceUsedUnit1,
  InterfaceUsedUnit2;

//...

Procedure AddRef;
Procedure Release;

Implementation

Uses
  ImplementationUsedUnit;

Procedure Init;
Begin
  InterfaceUsedUnit1.AddRef;
  InterfaceUsedUnit2.AddRef;
  ImplementationUsedUnit.AddRef;
  //.. code from original initialization section goes here
End;

Procedure Done;
Begin 
  //.. code from original finalization section goes here
  ImplementationUsedUnit.Release;
  InterfaceUsedUnit2.Release;
  InterfaceUsedUnit1.Release;
End;

Var
  RefCount: Integer;

Procedure AddRef;
Begin
  If LockedInc(RefCount) = 1 then
    Init; 
End;

Procedure Release;
Begin
  If LockedDec(RefCount) = 0 then
    Done;
End;

Initialization
  AddRef;
Finalization
  Release;
End.




More information about the fpc-devel mailing list