I have a question related to the static class member in C++. Based on my understanding of C++, the static class number is supposed to exist before the class’s instance is created. It is possible to initialize the const static member variable, but for the non-const static member we cannot initialize it within the class. Therefore, my question is where we should initialize the non-const static class. It seems to me that the only stage for the non-const static class is before the main program is run as the following codes illustrate:
using namespace std;
class C
{
public:
static int Value;
};
int C::Value = 2;
int main()
{
// int C::Value = 2; //ERROR!
cout<<C::Value<<endl;
return 0;
}
Are there other ways to initialize it? Thanks!
Non-local objects in C++ program can be initialized statically and dynamically. In simple terms, static initialization is trivial C-style initialization with constant expressions that is essentially performed at compile-time (and, therefore, generates no code). Meanwhile dynamic initialization is initialization that involves some non-trivial actions that have to be performed at run time.
You can assume that statically initialized objects begin their life in already initialized state. I.e. conceptually they are instantly initialized when your program starts.
When it comes to dynamic initialization time and order, static class members are treated the same way as any other namespace-scope object. The language does not guarantee that all objects with static storage duration are initialized before
main. Instead, the language guarantees that such static objects are initialized sometime before the first use of any function or object defined in the same translation unit. Static objects defined in the same translation unit are initialized in the order of their definition. The rules of dynamic initialization allow for the already mentioned “initialization order fiasco”.In your example – an
intobject initialized by an integral constant expression – static initialization will be used. It is safe to assume that thisintobject begins its life in already initialized state.