1

Consider the code:

#include <unordered_map>
#include <array>
#include <iostream>
int main () {
        std::unordered_map<int, std::array<int, 5>> map;
        map[42][0] = 1;
        for (int i = 0; i < 5; i++) {
                std::cout << map[42][i] << " ";
        }
}

This prints 1 0 0 0 0 on my system. The content of std::array held inside std::map was value-initialized upon insertion (i.e. all integers inside array were set to 0). Does the standard guarantee this? I should never expect the array used as value of the map to contain garbage?

lukeg
  • 4,189
  • 3
  • 19
  • 40
  • Does this answer your question? [Default initialization of std::array?](https://stackoverflow.com/questions/18295302/default-initialization-of-stdarray) – brc-dd Jun 30 '20 at 12:10

1 Answers1

1

operator [] inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T()))

T() means default initialization

since c++17 This function is equivalent to return this->try_emplace(key).first->second

emplace/try_emplace constructs default-initalized value in case of operator []

from https://en.cppreference.com/w/cpp/container/map/operator_at

Alexander
  • 698
  • 6
  • 14
  • you are quoting from the pre-c++11 part of the reference. Though answer is same – 463035818_is_not_an_ai Jun 30 '20 at 12:00
  • @idclev463035818 thanks. added to the answer – Alexander Jun 30 '20 at 12:12
  • fwiw if I understood the note about LWG issue 2469 correctly, what you had first is actually what is in the published c++11 and c++14 standards – 463035818_is_not_an_ai Jun 30 '20 at 12:14
  • But default initialization on an array of primitive type doesn't actually provide default initialize items inside. `std::array arr` would give indeterminate values. You have to do a zero init to it – Ranoiaetep Jun 30 '20 at 12:32
  • @Ranoiaetep array behaves just like int. pls compare ```int a```. and ```int a{}```. the behavior of array is the same. map forces the default initialization to 0. – Alexander Jun 30 '20 at 12:38
  • 2
    This answers my question, but T() does not mean default-initilization, it means value-initialization, at least since C++03 (https://en.cppreference.com/w/cpp/language/value_initialization) – lukeg Jun 30 '20 at 12:53
  • Sorry, that wasn't quite convincing. However found better explanation in the ISO n4835 draft: 9.4.0.7: To default-initialize an object of type T means:' 9.4.0.7.2: If T is an array type, each element is default-initialized' – Ranoiaetep Jun 30 '20 at 12:58
  • @lukeg that works, per ISO n4835 draft: 9.4.0.8: To value-initialize an object of type T means:' 9.4.0.8.3: If T is an array type, each element is value-initialized' – Ranoiaetep Jun 30 '20 at 13:08