Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unordered_map initialization

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)?

Example:

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

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

like image 603
Suma Avatar asked Jan 20 '12 14:01

Suma


People also ask

Is unordered_map initialized to 0?

And zero initialization of an int naturally initializes that int to 0 [dcl. init]/6. So yes, your code is guaranteed to return 0…

How do you initialize a value on a map?

We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

How is unordered_map implemented in C++?

Internally unordered_map is implemented using Hash Table, the key provided to map is hashed into indices of a hash table which is why the performance of data structure depends on the hash function a lot but on average, the cost of search, insert, and delete from the hash table is O(1).


1 Answers

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

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 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.

As to T(), the exact language is a somewhat involved, so I'll try to quote the relevant bits:

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;

like image 74
NPE Avatar answered Oct 12 '22 01:10

NPE