std::map 中原始类型的值是否已初始化? [英] Is the value of primitive types in std::map initialized?
本文介绍了std::map 中原始类型的值是否已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
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.
I thought the the values printed out would be undefined because primitive types doesn't have default constructor, but here I got 10000 1s every time I tested.
为什么要初始化?
推荐答案
当调用 operator[]
并且键丢失时,使用表达式 mapped_type()
初始化值code> 是类类型的默认构造函数,整数类型的初始化为零.
When invoking operator[]
and the key is missing, the value is initialized using the expression mapped_type()
which is the default constructor for class types, and zero initialization for integral types.
这篇关于std::map 中原始类型的值是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文