C++ Global variables and initialization order

后端 未结 1 1448
春和景丽
春和景丽 2021-01-16 03:24

Let\'s say, I\'ve got a following simple code:

Main.cpp

#include \"A.h\"

// For several reasons this must be a global variable in t         


        
1条回答
  •  隐瞒了意图╮
    2021-01-16 03:49

    It sounds like you are trying to force the initialization of the static to happen before the constructor is called. The last time I encountered this problem, the only reliable fix was to wrap the static inside a function.

    Change the declaration to a function returning reference to string.

    static std::string& myString();
    

    Change the definition to a function like this:

    std::string& A::myString() {
         static std::string dummy = "test";
         return dummy;
    }
    

    Change your constructor to say:

    myString() += "1";
    

    I do not currently have an MSFT compiler handy, so you may have to tweak this a little bit, but this basically forces on-demand initialization of static.

    Here is a very short test programming demonstrating how this works:

    #include 
    #include 
    
    
    std::string& myString() {
         static std::string dummy = "test";
         return dummy;
    }
    
    int main(){
        myString() += "1";
        printf("%s\n", myString().c_str());
    }
    

    0 讨论(0)
提交回复
热议问题