[comp.lang.c++] sequence of initialisation of objects

teege@lan.informatik.tu-muenchen.dbp.de (Gunnar Teege) (06/15/90)

I just found a problem with initialisation of global objects, when the
initialisation of one object depends (implicitly by using the other
one as a global object) on another one being initialised.

I am using arrays to allocate dynamically generated objects. Before
allocating the first object, the array has to be initialised (to
install a free-list). If the constructor for some class allocates
parts of the object in such an array, it will only succeed, when
this constructor is called after the constructor for the array.
This bug is hard to find. With CC 1.20 the sequence of constructing
global objects depend on the alphabetical ordering of the SOURCE
FILES, the global objects are declared in. (Did you ever meet a bug
that disappeared when renaming a source file? - It took me 6 hours
to trace the problem down.)

Of course, it is no good style to use a global object in any
function. But for the described use it seems quite natural. Has this
problem already been considered? Are there versions of c++ where it
is possible to have influence on the order in which global objects
are constructed?

For the curious: The exact way CC 1.20 works is:
For each source file xxx.C with global objects declared a function
called _STIxxx_C_ is declared by cfront which calles the constructors.
CC links all files together, calls 'nm' with the generated object
and feeds the output into a special program 'munch', which generates
a file __ctdt.c containing the declaration of a
pointer-to-function-array _ctors with all functions starting with _STI.
These are called by __main(), which is inserted at the beginning of
main() by cfront. The ordering in this array is the reversed lexical
ordering. In this order the functions are called.

Gunnar Teege   Inst. fuer Informatik, Technische Universitaet Muenchen
               PO-Box 202420, 8000 Muenchen 2,  West-Germany
teege@lan.informatik.tu-muenchen.dbp.de        +49 89 2105 8179
teege%lan.informatik.tu-muenchen.dbp.de@{unido.uucp,relay.cs.net,unido.bitnet}