Consider the following code:
map<int,int> m;
for(int i=0;i<10000;++i) m[i]++;
for(int i=0;i<10000;++i) printf("%d",m[i]);
I thought the the values printed out would be undefined because primitive types doesn't have default constructor, but here I got 10000 1s every time I tested.
Why is it initialized?
When invoking
operator[]
and the key is missing, the value is initialized using the expressionmapped_type()
which is the default constructor for class types, and zero initialization for integral types.In the C++14 standard, section
[map.access]
the text is:So, as also stated by Joseph Garvin's answer, the result of the expression
mapped_type()
is what is inserted. This sort of initialization is called value-initialization.The meaning of value-initialization is not quite as simple as offered in the other answers, for class types. It depends on what sort of constructors the class type has, and whether the class is an aggregate, as explained by the cppreference link.
For
int
as in this question, value-initialization means theint
is set to0
.See https://www.sgi.com/tech/stl/stl_map.h
In your example, _Tp is
int
, andint()
is 0In addition:
thanks to @MSalters who tells about code above is SGI instead of std::map, But I think it is some like...
std::map::operator[] inserts new value if it's not exist. If an insertion is performed, mapped value is initialized by default-constructor for class-types or zero-initialized otherwise.