Search code examples
c++dictionarystlinitializationprimitive-types

Do STL maps initialize primitive types on insert?


I have a std::map like this:

map<wstring,int> Scores;

It stores names of players and scores. When someone gets a score I would simply do:

Scores[wstrPlayerName]++;

When there is no element in the map with the key wstrPlayerName it will create one, but does it initialize to zero or null before the increment or is it left undefined?

Should I test if the element exists every time before increment?

I just wondered because I thought primitive-type things are always undefined when created.

If I write something like:

int i;
i++;

The compiler warns me that i is undefined and when I run the program it is usually not zero.


Solution

  • operator[] looks like this:

    Value& map<Key, Value>::operator[](const Key& key);
    

    If you call it with a key that's not yet in the map, it will default-construct a new instance of Value, put it in the map under key you passed in, and return a reference to it. In this case, you've got:

    map<wstring,int> Scores;
    Scores[wstrPlayerName]++;
    

    Value here is int, and ints are default-constructed as 0, as if you initialized them with int(). Other primitive types are initialized similarly (e.g., double(), long(), bool(), etc.).

    In the end, your code puts a new pair (wstrPlayerName, 0) in the map, then returns a reference to the int, which you then increment. So, there's no need to test if the element exists yet if you want things to start from 0.