Std :: unordered_map initialization

When I first get the std :: unordered_map element using the [] operator , it is automatically created. What (if any) are the guarantors of its initialization? (Guaranteed initialization of the value or only for its construction)?

Example:

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

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

+6
source share
2 answers

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

Yes. In the last line of your code, the value of size[test] initializes the T() element, or in this case size_t() :

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

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

1 Effects: If there is no key equivalent to x on the card, inserts the value__name (x, T () ) into the card.

As for T() , the exact language is somewhat involved, so I will try to bring the corresponding bits:

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

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


8.5.7 For value-initialize, an object of type T means:

- if T is a class of a class (possibly cv-qualit) ...

- if T is a (possibly cv-qualified) non-unit class ...

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

- , otherwise the object is initialized to zero.


8.5.5 For zero initialization, an object or reference of type T means:

- if T is a scalar type (3.9),, the object is set to 0 (zero) , taken as an integral constant expression, converted to T;

+16
source

What's the difference? Initializing values โ€‹โ€‹for objects of type class entails a default construct, so the answer is "both." For the map <K, V> new object will be initialized with V() .

All standard containers initialize new items with a value or direct initialization (the latter, possibly through copy building). It is impossible for the new standard container elements to be in an โ€œuninitializedโ€ state (i.e. there is no mechanism that initializes the elements by default).

0
source

Source: https://habr.com/ru/post/906488/


All Articles