c++ - 这个函数只会被调用一次吗?

标签 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 变量时,它是否每次都会运行“initConstMap”函数? const 映射显然是常量,因此不需要多次初始化。 (*注意主要的 cpp 是一个制造的例子,它并不是我的程序真正在做什么。我只是为了这个问题而简化事情)。

最佳答案

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

关于c++ - 这个函数只会被调用一次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269633/

相关文章:

python - 将多个字符串作为变量输入到以空格分隔的输入中

ios - 无法在深度嵌套的数据结构上下标错误

c++ - 将 vector 填充到 map 中

c++ - 这两个字符串有什么区别?

c++ - 模板化类中的关系运算符重载 (C++)

c++ - 将txt文件读入链表

c++ - 如何优化/重构这样的代码?

Swift3循环字典增加值

android - 如何使用自定义 Makefile 为 Android 编译 STL C++?

c++ - 在 C++ 中初始化一对数组