c++ - std::map<whatever,double> 是否自动将值归零?

标签 c++ std

<分区>

如果我写:

#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/

相关文章:

c++ - 基于四元数的相机不需要的滚动

c++ - 如何编写此西北方法的代码

c++ - 如果在此调用之前未创建 abcd,那么 `std::map<..> a; blah = a[abcd];` 线程安全吗?

c++ - std::packaged_task 编译错误 w/gcc 4.6

c++ - 使用 std::vector 作为简单缓冲区是一种好习惯吗?

c++ - 重载运算符和静态成员变量的行为

c++ - 为什么 lambda 没有从到达范围捕获类型 const double,而 const int 是?

C++ 有效地从用户定义结构的 vector 中提取子集

c++ - 如何在 Visual Studio C++ 项目中包含 <sys/select.h> 库?

error-handling - 字符串 io::Errors 是如何创建的