This was tested in SoloLearn's C++ Playground, I'm making the assumption my compiler will do something similar to the one SL uses.
So, I'm playing around with std::array<T, s>
, because I plan on using it in my game.
When I do std::array<bool, 5> def;
and print out the items in each index, I get:
Default 0: 0
Default 1: 0
Default 2: 0
Default 3: 0
Default 4: 0
When I do std::array<std::string, 5> def;
:
Default 0:
Default 1:
Default 2:
Default 3:
Default 4:
however, when I use an integral type like int
, I get numbers that are totally random in some of the spots. - Only a few are actually initialized with 0
(like I expect).
Here's a sample:
Default 0: 1875674416
Default 1: 32568
Default 2: 0
Default 3: 0
Default 4: 4199168
So, is there a way I can get these integral types to initialize properly? Or do I have to manually initialize the array with 0
(somehow)?
Top comments (4)
I'm actually not sure why your
bool
example works, maybe someone else can chime in. Your declaration is not an initialization. Thestd::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 forstd::string
because that's a class.To fix it, you can ask for value-initialization instead using
std::array<int, 5>{};
.We can't answer without a minimal code that reproduces that the issue.
Literally just do
std::array<NumericDatatype, 5> arr; /* Code to print. */
and you'll get similar results.arr
is not initialized. So its actual content is not specified.The behavior you observe is normal: there are random values in the array.
Sometimes, random values look like something you expect (like : all
bool
s arefalse
) but this is pure coincidence.