I'm trying to check the code again with Adam Pierce and added two more cases: a static variable in the class and a POD type. My compiler is g ++ 4.8.1, on Windows (MinGW-32). Result - the static variable in the class is treated the same as the global variable. Its constructor will be called before entering the main function.
(1) : The correct state must be: "before any function from the same translation unit is called." However, for simple, as in the example below, this is the 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
Has anyone tested on Linux env?
Thang Le Dec 03 '13 at 15:49 2013-12-03 15:49
source share