开发者

static variables initialization order between many classes

开发者 https://www.devze.com 2023-02-27 00:32 出处:网络
c.h class C{ static string s; } c.cpp string C::s=D::staticMethod(); d.h class D{ static string s; static string staticMethod();
c.h   
class C{  
    static string s;  
}

c.cpp  
string C::s=D::staticMethod();

d.h  
class D{  
static string s;  
static string staticMethod();  
}

d.cpp  
string D::s("some string");  
string D::staticMethod(){  
    return s;  (***)  
}

this won't work, it stops at (*) because D::s has开发者_如何转开发 not been initialized.Is there any way to get d.cpp compiled before c.cpp?


Best reference for this IMHO:

What's the "static initialization order fiasco"?


In short, no. If you really need this sort of behaviour, look up the Singleton pattern. But also think carefully whether you need that sort of coupling in your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号