函数级静态变量何时分配/初始化?

新手上路,请多包涵

我非常有信心在程序启动时分配(并初始化,如果适用)全局声明的变量。

 int globalgarbage;
unsigned int anumber = 42;

但是在函数中定义的静态函数呢?

 void doSomething()
{
  static bool globalish = true;
  // ...
}

globalish 的空间是什么时候分配的?我猜程序什么时候开始。但是它也会被初始化吗?还是在第一次调用 doSomething() 时初始化?

原文由 Owen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 665
2 个回答

我对此很好奇,所以我编写了以下测试程序并使用 g++ 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;
}

结果不是我所期望的。直到第一次调用函数时才调用静态对象的构造函数。这是输出:

 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

原文由 Adam Pierce 发布,翻译遵循 CC BY-SA 2.5 许可协议

我尝试再次测试 Adam Pierce 的代码并添加了另外两个案例:类中的静态变量和 POD 类型。我的编译器是 g++ 4.8.1,在 Windows 操作系统(MinGW-32)中。结果是类中的静态变量与全局变量相同。它的构造函数将在进入主函数之前被调用。

  • 结论(针对g++,Windows环境):
  1. 类中的 全局变量静态成员:在进入 函数 (1) 之前调用构造函数。
  2. 局部静态变量:仅在执行第一次到达其声明时才调用构造函数。
  3. 如果 局部静态变量是 POD 类型,那么在进入 main 函数 (1) 之前它也会被初始化。 POD 类型示例: static int number = 10;

(1) :正确的状态应该是: “在调用来自同一翻译单元的任何函数之前”。 但是,为了简单起见,如下例所示,它是 main 函数。

 #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;
    static test t; // static member
 };
test test::t("static in class");

test t("global variable");

void f()
{
    static  test t("static variable");
    static int num = 10 ; // POD type, init before enter main function

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

结果:

 static in class created
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
static in class destroyed

有人在 Linux 环境中测试过吗?

原文由 Thang Le 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏