std::map<whatever,double> 会自动将值归零吗?

Does std::map<whatever,double> automatically zero values?

如果我写:

#include <map>

int main()
{
    std::map<int, double> q;
    q[3] += 4;
    return 0;
}

我能确定 q[3] 是 4,而不是 q[3] 是 4 +(内存中一些随机未初始化的垃圾)吗?

如果映射中不存在 q[3],则会为您创建该记录并将值 初始化为零。

您的代码是安全的。

引用自cppreference.com

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

因此您可以指望初始化为零的值。

编辑:

上面引用的是C++11之前的情况。 C++11 及更高版本的措辞更难理解,但我认为这是执行语句:

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

第一个引用中的相同括号注释也适用于此处的术语 "value-initialized"(请参阅 the page on value initialization),因此它仍会将基本类型的初始化值置零。