这是我程序的相关部分
// constants.h
extern const std::map<std::string, int> constMap;
// constants.cpp
std::map<std::string, int> initConstMap()
{
//stuff required to initialize constMap
}
const std::map<std::string, int> constMap = initConstMap();
\\ main.cpp
...
for (int i = 0, n = LOTS_OF TIMES; i < n; ++i){
doSomethingWith(constMap[i]);
}
...
我想知道,每当我在主程序中使用 constMap 变量时,它是否每次都会运行“initConstMap”函数? const 映射显然是常量,因此不需要多次初始化。 (*注意主要的 cpp 是一个制造的例子,它并不是我的程序真正在做什么。我只是为了这个问题而简化事情)。
最佳答案
是的,它只会被调用一次,如果你问的是这个特定的代码片段——实际上它不能被调用更多次,因为它是 const
,而 const
禁止重新定义变量。然而,您可以做的是将您的结构更改为 constexpr
,这样一切都在编译时完成 - 这就是您所追求的。
关于c++ - 这个函数只会被调用一次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269633/