The lifetime of function static
variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.
Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example
struct emitter {
string str;
emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
~emitter() { cout << "Destroyed " << str << endl; }
};
void foo(bool skip_first)
{
if (!skip_first)
static emitter a("in if");
static emitter b("in foo");
}
int main(int argc, char*[])
{
foo(argc != 2);
if (argc == 3)
foo(false);
}
Output:
C:>样本.exe
创建于 foo
在 foo 中被破坏
C:>样本.exe 1
创建于 if
创建于 foo
在 foo 中被破坏
毁于如果
C:>样本.exe 1 2
创建于 foo
创建于 if
毁于如果
在 foo 中被破坏
[0]
Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.
[1]
C++98部分3.6.3.1
[基本.开始.术语]
[2]
在 C++11 中,静态变量以线程安全的方式初始化,这也称为魔法静力学.