gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:01:55 24 4
gpt4 key购买 nike

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

int globalgarbage;
unsigned int anumber = 42;

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

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

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

最佳答案

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

关于c++ - 函数级静态变量何时分配/初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com