There is a same question here : When exactly is constructor of static local object called?
but it only mentions on local static object, so i want add one more case for global static object.
Say we have 2 examples code like this:
Exam 1. local static ==========
class Mix {
Mix() { //the ctor code }
};
Mix& globalFunction()
{
static Mix gMix; // when its ctor execute ?
return gMix;
}
Exam 2. global static ==========
class Mix {
Mix() { //the ctor code }
static MyClass MReen; // when its ctor execute ?
};
//initialization static var
MyClass Mix::MReen = 0 ;
- When exactly 'the constructor code' of 2 static objects above is executed ?
- How is it on different between g++ (run on Linux) and VC++ compiler ?
Thanks
I try to test again code from Adam Pierce at here, and added two more cases: static variable in class and POD type. My compiler is g++ 4.8.1, in Windows OS(MinGW-32). Result is static variable in class is treated same with global variable. Its constructor will be called before enter main function.
Conclusion (for g++, Windows environment):
(1): The correct state should be: "before any function from the same translation unit is called". However, for simple, as in example below, then it is main function.
include < iostream>
result:
Anybody tested in Linux env ?
Global static variable is initialised before
main()
, but if you have several files the order is not garantied even within one compiler. Here is related answers: http://www.parashift.com/c++-faq/static-init-order.html , Can the compiler deal with the initialization order of static variables correctly if there is dependency?p.s. You can guarantee the order for const static with one trick: