Adam Pierceからのコードをもう一度テストして、クラスの静的変数とPODタイプの2つのケースを追加しました。私のコンパイラは、Windows OS(MinGW-32)のg ++ 4.8.1です。結果は、クラスの静的変数はグローバル変数と同じように扱われます。そのコンストラクタは、メイン関数に入る前に呼び出されます。
結論(g ++、Windows環境の場合):
- クラスのグローバル変数と静的メンバー:コンストラクターは、メイン関数(1)に入る前に呼び出されます。
- ローカル静的変数:コンストラクタは、実行が最初に宣言に達したときにのみ呼び出されます。
- 場合はローカル静的変数はPOD型であり、それはまた入る前に初期化される主な機能(1) 。PODタイプの例:static int number = 10;
(1):正しい状態は、「同じ変換単位の関数が呼び出される前」です。ただし、以下の例のように、単純な場合はメイン関数です。
インクルード<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;
}
結果:
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
Linux envでテストした人はいますか?