Re: Can initialization of static class members be forced before main?
On 3 avr, 17:56, Carsten Fuchs <CarstenFu...@T-Online.de> wrote:
is it possible to guarantee that a static member of a class
that is in a different compilation unit than main(), is still
initialized before main()?
In practice, it is guaranteed, and a lot of code counts on it.
At least, as long as everything is statically linked; static
objects in dynamic linked modules will not be initialized before
the module is loaded (for obvious reasons). At least on the
systems I use (Solaris and Linux), they will be initialized
before you return from the dlopen which loads the module,
however. (But you'll have to count on system by system
guarantees here. C++ doesn't know about dynamic linking, and
Posix doesn't know about C++ and dynamic initialization of
static objects.)
Details:
My intention is to have "self registering" classes, by having
them have a static member object named "typeinfo" whose
constructor adds itself to a global list.
I do similar things a lot. Basically, the registry has to use
the singleton pattern, since you can't otherwise guarantee that
it is constructed before the other static objects (even if all
are constructed before main).
I've googled, and
the relevant quote from the standard seems to be:
3.6.2/1 [basic.start.init]
The initialization of nonlocal objects with static
storage duration (3.7) defined in a translation unit
is done before the first use of any function or
object defined in that translation unit. Such
initializations (8.5, 9.5, 12.1, 12.6.1) can be done
before the first statement of main() or deferred to
any point in time before the first use of a function
or object defined in that translation unit.
That is, whenever the initialization is deferred (as I can
reproduce with VC++ 2005),
To the best of my knowledge, there are no systems where the
initialization is "deferred", in the sense above. In fact, I
rather doubth that it is possible, since the "deferred"
initialization imposes a topological sort---even in the case of
cycles.
my classes fail to register themselves and so they're missing
from the global list.
In the scenario you described above, you have a problem even if
all of the initialization occurs before entering main.
Is there a way to make sure that such initialization is not
deferred (either for all nonlocal objects with static storage
duration, or just for a set of selected ones), but completed
before main() begins?
Quality of implementation. No known compiler defers it, and no
new compiler would dare to defer it, given the amount of code
that would break.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34