简体   繁体   中英

static class member in c++

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. Ie 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 int object initialized by an integral constant expression - static initialization will be used. It is safe to assume that this int object begins its life in already initialized state.

You pretty much hit the nail on the head.

It doesn't matter whether you write the definition before or after main . In fact, aside from taking the static initialisation order fiasco into account, it doesn't matter where you write it at all, as long as the declaration (ie that line inside the class definition) is visible where you use the member, and as long as you do it in the same scope as the class definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM