Is the value of primitive types in std::map initialized?

醉酒当歌 提交于 2019-12-12 10:31:56

问题


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);

  1. Effects: If there is no key equivalent to x in the map, inserts value_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!