I am new to C++ and currently reading Bjarne Stroustrup's "Principle and Practice using C++". In chapter 8.6.2 about why global variables are bad, he gives the following example which can solve the problem of static initialization fiasco:
const Date& default_date() { static const Date dd(1970,1,1); // initialize dd first time we get here return dd; }The static local variable is initialized (constructed) only the first time its function is called. Note that we returned a reference to eliminate unnecessary copying and, in particular, we returned a const reference to prevent the calling function from accidentally changing the value.
Some time after, I was reading in this StackOverflow post about static data members in classes:
Static members exist before any object is created, that is what makes them static. Therefore their initialization does not happen on first instance, they are there already.
They are actually global variables within a class scope.
That said, you can use the inline modifier to initialize them inside the class without an out of class declaration.
From this, I take it that static variables defined inside a function and class definition have different properties? For example, that the static variable inside the function is defined the first time the function is executed, while a static variable inside a class is defined before any objects are created/when class definition is read by the compiler.
Are there any more differences between the two?
staticin C++ cannot be associated with its usage like this. The usages ofstatichave nothing to do with each other. You havestaticclass members,staticvariables in functions,staticmember functions,staticvariables declared at file scope, etc. etc. Each one is different from the other, so comparing and contrasting the usages doesn't make a lot of sense.default_datesolves the initialization order problem, butddwill be destroyed in reverse order to when it was created, and that might be a little harder to predict a little harder to get right. Still, this beats the crap out of the nigh-impossible to get right of the initialization order.