这个函数只会调用一次吗?

时间:2015-12-14 14:37:20

标签: c++ dictionary stl constants

以下是我的计划的相关部分

// 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变量,它都会运行&#34; initConstMap&#34;每次都有功能吗? const映射显然是常量,因此不需要多次初始化。 (*注意主要的cpp是一个制造的例子,它不是我的程序正在做的事情。我只是为了问题简化了事情。)

3 个答案:

答案 0 :(得分:3)

是的,它只会被调用一次,如果你问这个特定的代码片段 - 实际上它不能被调用更多次,因为它是const,并且const禁止重新定义变量。然而,你可以做的是将你的结构改为constexpr,所以一切都在编译时完成 - 这就是你所追求的。

答案 1 :(得分:1)

如果你只调用一次,那么该函数只会被调用一次。当调用初始化全局变量时,它也将在main之前调用。

要小心,不要经历the static initialization order fiasco

答案 2 :(得分:0)

如评论中所述,您实际上可以计算调用initConstMap函数的次数,但查看代码时,只调用一次。

请注意,这意味着每次调用constants.cpp的相关部分时,因此根据程序的其余部分,可能会更频繁地调用它。当然,它不会从for循环调用。