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.
(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>
#include < string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
static test t; // static member
};
test test::t("static in class");
test t("global variable");
void f()
{
static test t("static variable");
static int num = 10 ; // POD type, init before enter main function
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
result:
static in class created
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
static in class destroyed
Anybody tested in Linux env ?