Will this function be called only once?

Here is the relevant part of my program

// 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]);
}
...

I wonder if every time I use the constMap variable during my main program, will it run the initConstMap function every time or not? The const map is obviously constant and therefore does not need to be initialized many times. (* Note that the main cpp is a custom-made example, this is not what my program does. I am simply simplifying things for the sake of the question).

+4
source share
3 answers

, , - , const const . constexpr, - , .

+3

, . , main.

, .

+1

, , initConstMap, , , .

Please note: this means that each time the corresponding part of the constant .cpp is called, therefore, depending on the rest of your program, this may be called more often. Of course, it is not called from the for loop.

0
source

Source: https://habr.com/ru/post/1619910/


All Articles