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?
Yes. In the last line of your code,
size[test]
value-initializes the element toT()
, or in this casesize_t()
:As to
T()
, the exact language is a somewhat involved, so I'll try to quote the relevant bits:What's the difference? Value-initialization for class-type objects entails default construction, so the answer is "both". For a map
<K, V>
, the new object will be initialized withV()
.All standard containers initialize new elements with value- or direct-initialization (the latter possibly through a copy construction). It is not possible for new standard container elements to be in an "uninitialized" state (i.e. there is no mechanism that default-initializes elements).