简体   繁体   中英

Is static variable guaranteed to be initialized when used by static methods in the same translation unit?

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM