3

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

Community
  • 1
  • 1
Thang Le
  • 1,419
  • 1
  • 17
  • 25
  • `Mix::MReen = 0` is an assignment, not an initialization, and it's not allowed at global scope. prepend `MyClass` to it to make it an initialization, although initializing to 0 is redundant. – uk4321 Dec 01 '13 at 06:14
  • Answer is here: http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function – Andrey Mishchenko Dec 01 '13 at 06:16
  • Thanks, i was lack MyClass. Updated. – Thang Le Dec 01 '13 at 07:20

2 Answers2

4

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. Global variable and static member in class: constructor is called before enter main function (1).
    2. Local static variable: constructor is only called when execution reaches its declaration at first time.
    3. If Local static variable is POD type, then it is also initialized before enter main function (1). Example for POD type: static int number = 10;

(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 ?

Community
  • 1
  • 1
Thang Le
  • 1,419
  • 1
  • 17
  • 25
3
  1. A local static variable, declared in an function, is initialised before the first call to the function. You can read more about this aspects of C++ standard here https://stackoverflow.com/a/58804/747050.
  2. 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;
    }
    
Community
  • 1
  • 1
klm123
  • 12,105
  • 14
  • 57
  • 95
  • Many compilers order creation of static objects by the order of the object files during linking. If this is so, this should be mentioned in the docs for the compiler. – Kirill Kobelev Dec 01 '13 at 07:26
  • What does your first sentence mean? What function call? – user207421 Dec 01 '13 at 07:27
  • @EJP, in this case globalFunction() call. – klm123 Dec 01 '13 at 07:30
  • Then I believe you're mistaken. It is guaranteed to have executed before the function is called, but not necessarily 'at first call'. – user207421 Dec 01 '13 at 07:44
  • Hi, some people told me that the constructor of local static object (here is _Mix_) is only called once the function _globalFunction_ is called at first time. But some others ideas told that the constructor is called before main, it should be during dll loading time. So, what's correct one ? – Thang Le Dec 01 '13 at 08:04
  • @ThangLe, the constructor is called when an instance of the class is declared. If you make an instance local it won't be called before main(). – klm123 Dec 01 '13 at 08:10
  • @klm123: assuming that there is a local static variable was declared in a _dll_ that my application is linking to. In my application, it never references to function holding declaration of this static variable. so, ctor of this local static variable will be never called ? if that, it's quite serious because maybe ctor of this variable needs to be called for some reasons as initialize hardware... – Thang Le Dec 01 '13 at 08:23
  • @ThangLe, it Can be never called. It ctor needs to be called to initialize hardware, then probably you required to call the function or define the object instance before to use hardware? – klm123 Dec 01 '13 at 08:29
  • @klm123: please confirm again your first answer: `1 A local static variable, declared in an function, is initialised before the first call to the function. You can read more about this aspects of C++ standard here http://stackoverflow.com/a/58804/747050.` . It's correct ?. Because your link talks about _non-local objects_ – Thang Le Dec 01 '13 at 16:56
  • @ThangLe, have you read item 4 at the citation, which Arkadiy gave? "The zero-initialization (dcl.init) of all local objects... " – klm123 Dec 01 '13 at 17:02
  • @klm123: So, the constructor will be called before execution reaches its declaration at first time ?. From item 4, I think this rule is only applied for POD type. Quite confusing, some people told constructor is executed before the first call to the function. Somebody think it is only called in the first call to function. There need a method to test this case. – Thang Le Dec 03 '13 at 14:36
  • @ThangLe, I am confused already. This discussion is too long. Better create separate quesion where describe the situation in details. – klm123 Dec 03 '13 at 14:39
  • @klm123: from your link quoted, check example of Adam Pierce. It quite clear to see that constructor is only called in the first call to function :)). I will write a test for this again to confirm. you can comment in example code of Adam Pierce if needed. Because this discussion too long, so we should stop here. – Thang Le Dec 03 '13 at 14:58
  • The answer is not accurate. A local static object is initailized when the control passes over its definition for the first time (not "before the first call to the function"). If the control never passes over the defintion, the object is never initialized, even if the containing function itself is called many times. A global static object is not necessarily initailized before `main`. The language says that it is initialized before any function from the same translation unit is called, which can easily happen after `main` begins executing. – AnT stands with Russia Dec 03 '13 at 16:36
  • @ AndreyT: agree with you. even it is global object then it is not necessary to initialize before main. – Thang Le Dec 04 '13 at 13:11