问题
I had a value that I decided could be static. I decided to initialize the default on the definition, but the Constructor would load in any saved changes from last run (say static function Load()). Only finding that the constructor is called before static initialization so Load() changes get lost. Example below, we end up with m_var 7 instead of 2.
class x
{
public:
x() { Load(); };
static void Load();
static int m_var;
};
int x::m_var=7;
void x::Load()
{
m_var=2;
}
class y
{
public:
static x whatever;
};
x y::whatever;
main()
{
y *p=new y;
// y::whatever.m_var == 7 not 2
}
What is the normal way of handling this so I don't have to think about the initialization in each app and then try to figure out where to call it?
If you don't understand the question, read the above again, try to comprehend it, it's very clear what the problem is (order of initialization) and the question is how it is normally handled? For now, I did the dumb thing and call Load() inside of main() just before it would be used anywhere. But it should be automatic.
来源:https://stackoverflow.com/questions/62646907/c-rules-of-initialization-constructor-before-static-members