std::map::operator[]

std::map::operator[]

我正在做一个简单的地图程序,但最终遇到了这个问题。 C++ 文档是这样说的:

访问元素 如果 k 与容器中元素的键匹配,则函数 returns 对其映射值的引用。 如果 k 不匹配容器中任何元素的键,该函数将插入一个具有该键的新元素和 returns 对其映射值的引用。请注意,这总是将容器大小增加一,即使没有为元素分配映射值(元素是使用其默认构造函数构造的)。

我没有真正理解的部分是 "the element is constructerd using its default constructor"。

我试了一下,做了这个

std::map<string, int> m;
m["toast"];

我只是想看看 "toast" 的映射元素的值是多少。它最终为零,但是,为什么呢?基本类型有默认构造函数吗?或者发生了什么事?

映射值由operator[]值初始化,对于int意味着零初始化。

如标准 (§23.4.4.3) 所定义:

Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

T() 解释为 (§8.5/10):

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized ​

这意味着 (§8.5/8):

To value-initialize an object of type T means:

[...]

— otherwise, the object is zero-initialized.

零初始化定义为(§8.5/6):

To zero-initialize an object or reference of type T means:

— if T is a scalar type, the object is set to the value 0 (zero), taken as an integral constant expression, converted to T

[...]

所有引用自 n4140

"using its default constructor"的说法令人费解。更准确地说,对于 std::map::operator[], if the key does not exist, the inserted value will be value-initialized.

When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.

对于int,表示zero-initialization

4) otherwise, the object is zero-initialized.