什么时候创建全局变量? [英] When are global variables created?
问题描述
我有一个这样的代码结构:
I have a piece of code structured like this:
a.cpp:
#include "b.hpp"
const unsigned a = create(1);
b.cpp:
map<int, string> something; // global variable
unsigned create(unsigned a){
something.insert(make_pair(a, "somestring"));
return a;
}
现在,这会抛出一个segfault,valgrind表示映射尚未创建。
Now, this throws out a segfault, valgrind says that map was not yet created. How does it work, how should I change it?
推荐答案
在程序中构造全局变量时,C ++没有定义一个顺序启动。 a 可以在
某些
被构造之前被初始化,这将导致上述问题。当你开始构造全局变量,依赖于被初始化的其他全局变量时,你会遇到古典的静态初始化顺序fiasco 。
C++ does not define an order for when global variables are constructed during program startup. a
could be initialized first before something
gets constructed which would cause the problem above. When you start constructing global variables that depend on other global variables being initialized then you run into the classical static initialization order fiasco.
修复你的上述情况是使某事
static并移动到你的创建
函数。
An easy way to fix your above scenario is to make something
static and move it into your create
function.
unsigned create(unsigned a)
{
static map<int, string> something;
something.insert(make_pair(a, "somestring"));
return a;
}
这将保证某些
在第一次调用 create
时创建。
That will guarantee something
gets created on first call to create
.
这篇关于什么时候创建全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!