Reputation: 1449
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 ;
Thanks
Upvotes: 3
Views: 8673
Reputation: 1449
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>
#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 ?
Upvotes: 4
Reputation: 12865
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:
int YourClass::YourStaticVar()
{
static const int value = 0;
return value;
}
Upvotes: 3