DEV Community

Discussion on: Why do integral types get weirdly initialized inside of std::array in C++, and how can I fix it?

Collapse
 
deciduously profile image
Ben Lovy

I'm actually not sure why your bool example works, maybe someone else can chime in. Your declaration is not an initialization. The std::array will perform default initialization, which crucially is not the same as value-initialization. For primitive types, each element is undefined, meaning it has garbage. It's different for std::string because that's a class.

To fix it, you can ask for value-initialization instead using std::array<int, 5>{};.