static変数初期化
1.C++では、グローバルstatic変数とclassのstaticメンバー変数はmain関数の前に初期化され、main関数の後に破棄されます.
2.関数内部のローカルstatic変数は、この関数が最初に呼び出されたときに初期化され、main関数の後に破棄されます.
3.staticデータは、関数内部のオブジェクトであってもグローバルデータ領域に格納され、グローバルデータ領域のデータは、関数の終了によって空間を解放することはありません.
output:
create main begin main end destroy
output:
create main begin main end destroy
main begin first create second main end destroy
BTのテーマを比較しています.
システムでは1回しか関数を呼び出せません
2.関数内部のローカルstatic変数は、この関数が最初に呼び出されたときに初期化され、main関数の後に破棄されます.
3.staticデータは、関数内部のオブジェクトであってもグローバルデータ領域に格納され、グローバルデータ領域のデータは、関数の終了によって空間を解放することはありません.
#include <iostream>
using namespace std;
struct Date
{
Data(){cout<<"create"<<endl;}
~Data(){cout<<"destroy"<<endl;}
};
static Data g_sData;
int main()
{
cout << "main start" << endl;
cout << "main end" << endl;
return 0;
}
output:
create main begin main end destroy
#include <iostream>
using namespace std;
struct Date
{
Data(){cout<<"create"<<endl;}
~Data(){cout<<"destroy"<<endl;}
};
class Test
{
static Data m_sData;
};
Data Test::m_sData;
int main()
{
cout << "main start" << endl;
cout << "main end" << endl;
return 0;
}
output:
create main begin main end destroy
#include <iostream>
using namespace std;
struct Date
{
Data(){cout<<"create"<<endl;}
~Data(){cout<<"destroy"<<endl;}
};
void test()
{
static Data sData;
}
int main()
{
cout << "main start" << endl;
cout << "first time call test" << endl;
test();
cout << "second time call test" << endl;
test();
cout << "main end" << endl;
return 0;
}
main begin first create second main end destroy
BTのテーマを比較しています.
システムでは1回しか関数を呼び出せません
void caller()
{
cout<<"first call
";
}
void FirstCall()
{
static int d = (caller(),1);
}
int main()
{
FirstCall();
FirstCall();
}