問題描述
我非常有信心全局聲明的變量在程序啟動時被分配(并初始化,如果適用).
I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
int globalgarbage;
unsigned int anumber = 42;
但是在函數中定義的靜態函數呢?
But what about static ones defined within a function?
void doSomething()
{
static bool globalish = true;
// ...
}
global
的空間是什么時候分配的?我猜程序什么時候開始.但是它也被初始化了嗎?還是在第一次調用 doSomething()
時初始化?
When is the space for globalish
allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething()
is first called?
推薦答案
我對這個很好奇所以寫了下面的測試程序,并用g++ 4.1.2版本編譯.
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
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;
};
test t("global variable");
void f()
{
static test t("static variable");
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;
}
結果出乎我的意料.直到第一次調用該函數時,才調用靜態對象的構造函數.這是輸出:
The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:
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
這篇關于什么時候分配/初始化函數級靜態變量?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!