Re: initialising static member with static methode
On Oct 24, 3:25 pm, Jens Henrik Goebbert <goebb...@itv.rwth-aachen.de>
wrote:
I have some kind of tricky question on the c++ internals.
There must be some rule in what order static members get initialised.
Sort of. There are actually a lot of rules: everything gets
"zero initialized" first, then static initialization occurs,
then dynamic initialization. Dynamic initialization occurs in
the order of definition within a translation unit; the order of
dynamic initialization between translation units is unspecified.
Typically, it's that last rule that causes people problems, and
requires extensive work-arounds.
I need to initialise a static member (m_sPropertyInfos) using a static
methode (initStaticPropertyInfos). This static methode uses a static
member staticMetaObject of the superclass.
If the initialization of m_sPropertyInfos uses a function, it is
dynamic initialization. If staticMetaObject also requires
dynamic initialization, and is defined in a different
translation unit, you have a problem.
Will that work with all compilers (it is fine with gcc-4.x)
myfile.cpp:
/*static*/ QList<AXPropertyInfo*> AXData::initStaticPropertyInfos() {
QList<AXPropertyInfo*> propertyInfos;
for(int i=0; i<staticMetaObject.propertyCount(); i++) {
propertyInfos.append(0);
}
return propertyInfos;
}
QList<AXPropertyInfo*> AXData::m_sPropertyInfos = initStaticPropertyInf=
os();
Unless staticMetaObject has static initialization (trivial
constructor, only constant expressions used in a {...} style
initialization), this doesn't reliably work with any compiler I
know, including g++ 4.1.0, unless staticMetaObject is defined in
the same translation unit. Whether it happens to work on any
given day will typically depend on link order, which, if the
object files are in a library, may vary from one link to the
next.
You probably need to use some variant of the singleton idiom for
staticMetaObject.
--
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