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

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?

Upvotes: 0

Views: 55

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

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

Upvotes: 1

Related Questions