C++ 函数中静态变量的生命周期是多少? [英] What is the lifetime of a static variable in a C++ function?

查看:34
本文介绍了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变量从第一次[0]程序流程遇到声明开始它在程序终止时结束.这意味着运行时必须执行一些记账操作,以便只有在实际构建时才销毁它.

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.

另外,由于标准规定静态对象的析构函数必须按照其构造完成的相反顺序运行[1],而构造的顺序可能取决于具体的程序运行,必须考虑施工顺序.

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.

示例

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
创建于 foo
在 foo 中销毁

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

C:>sample.exe 1
创建于 if
创建于 foo
在 foo
中销毁在 if 中销毁

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

C:>sample.exe 1 2
创建于 foo
创建于 if
在 if
中销毁在 foo 中销毁

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

[0] 由于 C++98[2] 没有引用多线程,这将如何在多线程中表现线程环境未指定,并且可能会出现问题 罗迪提及.

[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 [basic.start.term]

[2] 在 C++11 中,静态以线程安全的方式初始化,这也称为 魔术静态.

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆