3

If i initialize a std::vector like this:

vector<int> sletmig(300);

will it set all the 300 values to zero, or keep what was in my computer memory?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 4
    I'm voting to close this question as off-topic because it should be super easy to test it yourself. Moreover, they are similar questions around, should have found them with Google (or another search engine). Does not provide any new useful information to SO. – gsamaras Jun 11 '15 at 18:31
  • 6
    @gsamaras "Super easy" to distinguish between "initialized to all zeroes" and "happened to be all zeroes"? I doubt it. – T.C. Jun 11 '15 at 18:38
  • 2
    I agree with @T.C. if you use the "just test it method" on Undefined Behavior, for example. you'll just see the behavior that *your specific compiler chose to implement*, it is better to find what an authority (i.e. the standard) says is the defined behavior. In this case, it is perfectly defined behavior, that is specified in various references. – Cory Kramer Jun 11 '15 at 18:47
  • Yes a duplicate is a better solution. @T.C. you are right. – gsamaras Jun 11 '15 at 20:05

1 Answers1

5

They will be set to zero as the elements will be value-initialized.

From cppreference

explicit vector( size_type count );

Constructs the container with count default-inserted instances of T. No copies are made.

But know that you can also specify the default value of all the elements, for example

vector<int> sletmig(300, 0);

Again from cppreference

vector( size_type count, 
        const T& value,
        const Allocator& alloc = Allocator());

Constructs the container with count copies of elements with value value.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218