什么时候功能级静态变量获得分配/初始化? [英] When do function-level static variables get allocated/initialized?

查看:119
本文介绍了什么时候功能级静态变量获得分配/初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很有信心,全球声明的变量得到分配(并初始化,如适用)在节目开始时间。

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

当是 globalish 的空间分配?在程序启动时我猜。但是否得到初始化,然后呢?抑或是初始化时 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

这篇关于什么时候功能级静态变量获得分配/初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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