Victor Bazarov wrote:
Mike - EMAIL IGNORED wrote: MyClass
{
//I have a static member method:
void static myMethod();
//and a static data member:
static MyType myData;
};
//In the .cpp file:
void MyClass::myMethod()
{
if (myData == myInitialValue)
...
}
//and below, in the same file:
MyType MyClass::myData = myInitialValue;
Can I rely on initialization in time for the if
statement? Chapter and verse?
Objects with static storage duration (static data members included)
defined outside of any function scope are initialised before 'main'
is called. So, if youre 'myMethod' function is called in the course
of normal program execution, 'myData' will have been initialised.
If the 'myMethod' function is called during another static object
initialisation, all bets are off, unless that object is declared
_after_ 'myData' in the _same_ translation unit.
Actually, the complete answer is a little more complicated than that.
If MyType is a POD type, then it's garanteed to be initialized before
any global complex (non-POD) type. This includes static data members.
Even if not in same translation unit.
You can not ganrantee the order of initialization if MyType is a
non-POD type, and it's access from a global object's constructor that
is in a different translation unit.
An easy work around method for this is to create the object as a static
local variable within a static function.
class MyClass
{
void static myMethod();
//Replace above with following:
inline static MyType& GetMyData(){static MyType myData;}
};
Now your variable is garanteed to be initialized IAW C++ standard when
you call it.
However, if it's called from a global object's destructor, you will
still have issues with order of destructor.