Re: static initialization order issues
lhyatt@princeton.edu wrote:
I am trying to work around some issues related to
initialization order of static template members. I know this
order is unspecified, but I am wondering if I can at least be
sure it will happen after initilization of constants.
You can't in general. You can in some specific cases.
Here is what I mean:
--------------------------------
#include <string>
template<typename T>
struct A {
static const std::string s;
};
extern char const c[]="hello";
template<typename T>
const std::string A<T>::s(c);
int main(){}
------------------------------------
Is it guaranteed that c points to the string "hello" before A
is initialized?
In this case, yes.
It's important that c[] be declared extern for the actual
application I need. (But does that matter anyway for this
question?)
It doesn't matter. The key here is that c has a static
initializer. Basically, initialization is divided into three
steps: zero initialization, static initialization and dynamic
initialization. These steps always occur in that order, over
the entire program. (In practice, both static initialization
and zero initialization take place on program loading, before
the new process even starts.)
Basically speaking, if the object type has a trivial
constructor, and is initialized using a constant expression (or
constant expressions, in the case of an array), the
initialization is static. In this case, even if c were defined
in a different compilation unit, it would be initialized before
any dynamic initialization takes place. And since std::string
has non-trivial constructors, all initialization of std::string
is dynamic.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]