问题
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?
回答1:
When invoking operator[] and the key is missing, the value is initialized using the expression mapped_type() which is the default constructor for class types, and zero initialization for integral types.
回答2:
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.
回答3:
See https://www.sgi.com/tech/stl/stl_map.h
_Tp& operator[](const key_type& __k) {
iterator __i = lower_bound(__k);
// __i->first is greater than or equivalent to __k.
if (__i == end() || key_comp()(__k, (*__i).first))
__i = insert(__i, value_type(__k, _Tp()));
return (*__i).second;
}
In your example, _Tp is int, and int() is 0
#include <iostream>
using namespace std;
int main() {
int x = int();
cout << x << endl;
return 0;
}
In addition:
thanks to @MSalters who tells about code above is SGI instead of std::map, But I think it is some like...
回答4:
In the C++14 standard, section [map.access] the text is:
T& operator[](const key_type& x);
- Effects: If there is no key equivalent to
xin the map, insertsvalue_type(x, T())into the map.
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 the int is set to 0.
来源:https://stackoverflow.com/questions/38549057/is-the-value-of-primitive-types-in-stdmap-initialized