gpt4 book ai didi

c++ - std::unordered_map 初始化

转载 作者:可可西里 更新时间:2023-11-01 14:57:11 69 4
gpt4 key购买 nike

当我访问 std::unordered_map using operator [] 中的元素时第一次,它是自动创建的。关于其初始化的保证是什么(如果有的话)? (保证是值初始化,还是只构造)?

例子:

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] 将元素值初始化为 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++ - std::unordered_map 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8943261/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com