<分区>
如果我写:
#include <map>
int main()
{
std::map<int, double> q;
q[3] += 4;
return 0;
}
我能确定 q[3] 是 4,而不是 q[3] 是 4 +(内存中一些随机未初始化的垃圾)吗?
<分区>
如果我写:
#include <map>
int main()
{
std::map<int, double> q;
q[3] += 4;
return 0;
}
我能确定 q[3] 是 4,而不是 q[3] 是 4 +(内存中一些随机未初始化的垃圾)吗?
最佳答案
引自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.
第一个引用中的相同括号注释也适用于此处的术语“值初始化”(参见 the page on value initialization ),因此它仍然会将基本类型的初始化值置零。
关于c++ - std::map<whatever,double> 是否自动将值归零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48567505/