c – std :: unordered_map初始化

前端之家收集整理的这篇文章主要介绍了c – std :: unordered_map初始化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我第一次访问 std::unordered_map using operator []中的元素时,会自动创建它.什么(如果有的话)是关于它的初始化的保证? (保证值是初始化的,还是只能构建)?

例:

std::unordered_map<void *,size_t> size;
char *test = new char[10];
size[test] += 10;

在此序列结束时,尺寸[测试]是否保证为10?

解决方法

Is size[test] guaranteed to be 10 at the end of this sequence?

是.
代码的最后一行,size [test] value-将元素初始化为T(),或者在本例中为size_t():

C++11 23.4.4.3 map element access [map.access]

T& operator[](const key_type& x);

1 Effects: If there is no key equivalent to x in the map,inserts value_type(x,T()) into the map.

对于T(),确切的语言有点涉及,所以我将尝试引用相关的位:

C++11 8.5.16 The semantics of initializers are as follows.

If the initializer is (),the object is value-initialized.

8.5.7 To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type …

— if T is a (possibly cv-qualified) non-union class type …

— if T is an array type,then each element is value-initialized;

otherwise,the object is zero-initialized.

8.5.5 To zero-initialize an object or reference of type T means:

— 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;

猜你在找的C&C++相关文章