Sujet : Re: Pre-main construction order in modules
De : eesnimi (at) *nospam* osa.pri.ee (Paavo Helde)
Groupes : comp.lang.c++Date : 31. Mar 2025, 09:49:23
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vsdkuj$3rhjh$1@dont-email.me>
References : 1 2 3
User-Agent : Mozilla Thunderbird
On 30.03.2025 18:30,
Muttley@DastardlyHQ.org wrote:
On Sun, 30 Mar 2025 10:38:57 -0400
James Kuyper <jameskuyper@alumni.caltech.edu> wibbled:
Section 6.9.3.3 does in fact impose many constraints on the sequence in
which non-local objects with static storage duration get initialized.
However, all of the sequence requirements are only between objects
defined in the same translation unit. Also, it's implementation-defined
which of those initializations occur before the start of main().
Initialising global objects before main is an absolute must otherwise how
are you expected to use them safely? They're not in the code for decoration.
Initializing global objects before main is not possible with demand-loaded dynamically loaded libraries.
IIRC this clause in the standard (that it's implementation-defined which static initializations occur before the start of main()) was introduced in C++11 when they got around to recognize the existence of shared libraries. To make the global static variables usable there is now another clause ([basic.start.dynamic]):
"If [initialization] is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized."
In practice, it means it is a bad idea to expose global static variables directly from a TU or from a shared library, because it is tricky to tell when and if the exported address becomes safe to use, and this may change on a whim by the compiler version and optimization levels, etc. I think I have seen a compiler optimizing away the whole TU when it only contained static data and no functions with external linkage.