什么时候分配/初始化函数级静态变量?

When do function-level static variables get allocated/initialized?(什么时候分配/初始化函数级静态变量?)
本文介绍了什么时候分配/初始化函数级静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

global 的空间是什么时候分配的?我猜程序什么时候开始.但是它也被初始化了吗?还是在第一次调用 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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)