本文介绍了C ++函数中静态变量的生命周期是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果变量在函数的作用域中声明为 static ,它只会初始化一次,并在函数调用之间保留其值。它的寿命究竟是什么?它的构造函数和析构函数何时被调用?

If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?

void foo()
{
    static string plonk = "When will I die?";
}






对于那些想知道

推荐答案

函数的生命周期 static 变量从第一次开始,程序流遇到声明,并在程序终止时结束。这意味着运行时必须执行一些簿记,以便只有当它被实际构造时才会破坏它。

The lifetime of function static variables begins the first time 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 and the order of construction may depend on the specific program run, the order of construction must be taken into account.

示例

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);
}

输出

C:> sample.exe 1

创建于如果

创建于foo

在foo中销毁

摧毁在

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:> sample.exe 1 2

创建于foo

创建于如果

如果被破坏

在foo中销毁

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] code>由于 C ++ 98 没有引用多个线程如何在多线程环境中的行为是未指定的,可以是问题在于提及。

[0] Since C++98 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 [basic.start.term]

[2] code>在C ++ 11静态被初始化在线程安全的方式,这也被称为。

这篇关于C ++函数中静态变量的生命周期是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:23