Re: initialization sequence issue
On Jan 5, 7:17 pm, Christof Warlich <cwarl...@gmx.de> wrote:
the few lines of code below show different results depending on
the compiler version (gcc-2.95 versus gcc-3.3 and later):
gcc-2.95 first initializes d (line 9) and then t (line 8), as
running the executable yields
initialized d
X constructor
whereas gcc-3.3 and later gcc versions do as I'd expect: They
initialize the variables as they appear in the source code:
X constructor
initialized d
I'm not sure I'd have any expectations about this. Line 8
doesn't define anything.
Could anyone tell if the initialization sequence is specified
by the standard in such a case or if I cannot rely on the
initialization sequence even when everything is in the same translation
unit?
The standard guarantees that object definitions requiring
dynamic initialization occur in the order of the definitions
within a given translation unit. Note, however, that a static
member of a template is only "defined" if it is
instantiated---each instantiation is a separate definition (and
the template definition is *not* a definition of an object).
Because the point of instantiation will vary if the static
member is instantiated in several different translation units,
the standard simply says that the order in this case is
unspecified.
1 #include <stdio.h>
2 struct X {
3 X() {printf("X constructor\n");}
4 };
5 template<typename T> struct A {
6 static T t;
7 };
8 template<typename T> T A<T>::t;
Note that the above is a declaration, not a definition.
9 X &x = A<X>::t;
10 int d = printf("initialized d\n");
11 int main() {}
Just curious, but what do you expect to happen if A<X>::t is
also implicitely initialized in another translation unit?
I think you've got a case of unspecified behavior here.
--
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