std :: unordered_map初始化 [英] std::unordered_map initialization
问题描述
当我使用操作符[]访问 std :: unordered_map中的元素时首次自动创建.对其初始化有什么保证(如果有的话)?(保证要初始化值,还是只能构造)?
When I access an element in std::unordered_map using operator [] for the first time, it is automatically created. What (if any) are guarantees about its initialization? (It is guaranteed to be value initialized, or only to be constructed)?
示例:
std::unordered_map<void *, size_t> size;
char *test = new char[10];
size[test] += 10;
此序列末尾的size [test]是否保证为10?
Is size[test] guaranteed to be 10 at the end of this sequence?
推荐答案
此序列末尾的size [test]是否保证为10?
Is size[test] guaranteed to be 10 at the end of this sequence?
是的.在代码的最后一行, size [test]
值将元素初始化为 T()
,或者在这种情况下为 size_t()
:
Yes.
In the last line of your code, size[test]
value-initializes the element to T()
, or in this case size_t()
:
C ++ 11 23.4.4.3映射元素访问[map.access]
C++11 23.4.4.3 map element access [map.access]
T&运算符[](const key_type& x)
;
1效果:如果地图中没有等效于x的键,则将value_type(x, T())插入地图中.
1 Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
对于 T()
,确切的语言有些复杂,所以我会尝试引用相关的位:
As to T()
, the exact language is a somewhat involved, so I'll try to quote the relevant bits:
C ++ 11 8.5.16初始化程序的语义如下.
C++11 8.5.16 The semantics of initializers are as follows.
— 如果初始化器为(),则该对象将被值初始化.
8.5.7 值初始化类型T的对象的意思是:
8.5.7 To value-initialize an object of type T means:
-如果T是(可能具有cv限定的)类类型...
— if T is a (possibly cv-qualified) class type ...
-如果T是(可能具有cv资格的)非工会类类型...
— if T is a (possibly cv-qualified) non-union class type ...
-如果T是数组类型,则每个元素都将被值初始化;
— if T is an array type, then each element is value-initialized;
— 否则,该对象将被初始化为零.
8.5.5要零初始化一个类型为T的对象或引用,意味着:
8.5.5 To zero-initialize an object or reference of type T means:
-如果T是标量类型(3.9),则将对象设置为值0(零),将其作为整数常量表达式,转换为T;
— if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
这篇关于std :: unordered_map初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!