I have a following code:
#include <iostream>
#include <unordered_map>
#include <string>
int main()
{
std::unordered_map<std::string, int> map;
std::cout << map["foo"]; // -> 0
return 0;
}
I am using map["foo"]
without initialisation.
Is this code valid or UB?
Edit: I tried to compile in godbolt and got 0
output with clang and gcc (trunk version) https://godbolt.org/z/KeWq7nbob.
When operator[]
does not find the value with given key one is inserted into the map. From cppreference:
Inserts
value_type(key, T())
if the key does not exist. [...]
T()
is Zero-initialization. For int
this bullet applies:
If
T
is a scalar type, the object is initialized to the value obtained by explicitly converting the integer literal0
(zero) toT
.
All is fine in your code. map["foo"]
returns a reference to 0
after inserting that 0
together with the key constructed from the string literal "foo"
into the map. This is the intended use of std::map::operator[]
. If you want to check if an element exists in the map use std::map::find
. If you want to find an existing one or insert if none is present, use std::map::insert
.