std::map中原始类型的值是否初始化?

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

考虑以下代码:

map<int,int> m;
for(int i=0;i<10000;++i) m[i]++;
for(int i=0;i<10000;++i) printf("%d",m[i]);

我认为打印出来的值是未定义的,因为基本类型没有默认构造函数,但在这里我每次测试都得到 10000 个 1。

为什么要初始化?

当调用 operator[] 并且缺少键时,使用表达式 mapped_type() 初始化值,这是 class 类型的默认构造函数,以及整数类型的零初始化。

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

在你的例子中,_Tp 是 intint() 是 0

#include <iostream>
using namespace std;
int main() {
  int x = int();
  cout << x << endl;
  return 0;
}

另外:

感谢@MSalters,他告诉我们上面的代码是 SGI 而不是 std::map,但我认为它有点像...

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否则。

在 C++14 标准中,第 [map.access] 节的文本是:

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.

因此,正如 Joseph Garvin 的回答所述,表达式 mapped_type() 的结果就是插入的内容。这种初始化称为 value-initialization.

对于 class 类型,值初始化的含义并不像其他答案中提供的那么简单。这取决于 class 类型具有哪种构造函数,以及 class 是否是聚合,如 cppreference link 所解释的那样。

对于这个问题中的int,值初始化意味着int设置为0