When are static data initialized ?
I think:
It can be initialized by constructor,
or
when it is declared,
or outside of the class by
class A::member_d = 5; // member_d is static
others ?
Also, When do file scope static variables initialized and when do function scope static variables initizliaed?
I think they are initialized when they are declared.
thanks
Static Storage duration object initialization:
Note: Static member objects are initialized the same way as objects at file scope.
The object is initialized by the initializer in the definition. if you do not provide an initializer then it will be zero-initialized.
Static members are exactly the same as objects as file scope.
Now the order that they are initialized is harder to define. The order is deliberately left vague to allow for compiler and linker situations that the committee could not foresee.
It is defined in:
3.6.2 Initialization of non-local variables
The main thing to note is:
So in most situations they will all be fully constructed before main is entered.
As noted by others. The compiler is allowed to delay initialization.
3.6.2 Paragraph 4
This addition is mainly done to support dynamically loading libraries at runtime (which may by laded dynamically after main has started). But it does provide a simple guarantee that all static storage duration objects within a compilation until will be fully constructed before any objects or function in that compilation are used.
3.6.2 Paragraph 5
Static members of a class are initialized at the point of definition. Const integral data types are an exception that can be initialized at the point of declaration. When such initialization is going to be executed is somewhat complicated (google for static initialization fiasco). According to the standard:
Global variables are initialized at program start-up, before
main()
is invoked. Static objects that are local to a scope are initialized the first time execution passes over them.Static class members are just global variables, so see above.
Destruction of global and static objects happens after
main()
returns.(The implementation details of this are fairly intricate, since all the destructors have to be queued up for execution somewhere, and for local statics there needs to be a flag to indicate whether the object has already been instantiated.)
No, of course, the constructor can't initialize static data members. For const integral or enumeration types, you can initialize within the scope of the class definition. However, in general, you must initialize outside the class definition.