What happens if I don't pass the second parameter to std::vector's constructor?

56 views Asked by At

We can create std::vector in this way:

std::vector<int> numbers(n, value);

It is possible not to pass the second parameter to the constructor.
But are we guaranteed that if we create std::vector of ints' it will be filled with zeroes?

1

There are 1 answers

0
Vlad from Moscow On

If the initializer is not explicitly specified, the objects are value initialized using the construction T(). For fundamental types, as for example the type int, it means zero-initialization.

So, this declaration:

std::vector<int> numbers(n);

Is, in fact, equivalent to:

std::vector<int> numbers(n, 0);

Here is a demonstration program:

#include <iostream>
#include <vector>

int main()
{
    std::cout << std::boolalpha 
        << ( std::vector<int>( 10, 0 ) == std::vector<int>( 10 ) )
        << '\n';
}

The program output is

true