Reputation: 192
I read that the dynamic initialization of static global variables is guaranteed to happen in the order of definition if they are in the same translation unit. Then I wonder whether it is guaranteed that a static global variable must have been dynamic initialized when it is used by a static method defined after it in the same translation unit.
//Foo.h
class Foo
{
public:
Foo(int i) {m_i = i;}
int m_i;
};
//X.h
class X
{
static void doSth();
static Foo foo;
};
//X.cpp
Foo X::foo(2);
void X::doSth()
{
//Is it guaranteed that foo has been properly initialized here?
std::cout << foo.m_i << std::endl;
}
Upvotes: 2
Views: 73
Reputation:
Short answer: No, global initialization has nothing to do with static methods.
Here's a simple scenario that illustrates why: what if the constructor of Foo
invoked doSth()
?
If you need that guarantee, you need to use a function-scope static variable.
Upvotes: 4