C++ - value of uninitialized vector<int>

The zero initialization is specified in the standard as default zero initialization/value initialization for builtin types, primarily to support just this type of case in template use.

Note that this behavior is different from a local variable such as int x; which leaves the value uninitialized (as in the C language that behavior is inherited from).


It is not undefined behaviour, a vector automatically initialises all its elements. You can select a different default if you want.

The constructor is:

vector( size_type, T t = T() )

and for int, the default type (returned by int()) is 0.

In a local function this:

int x;

is not guaranteed to initialise the variable to 0.

int x = int();

would do so.

int x();

sadly does neither but declares a function.


The constructor you are using actually takes two arguments, the second of which is optional. Its declaration looks like this:

explicit vector(size_type n, const T& value = T())

The first argument is the number of elements to create in the vector initially; the second argument is the value to copy into each of those elements.

For any object type T, T() is called "value initialization." For numeric types, it gives you 0. For a class type with a default constructor, it gives you an object that has been default constructed using that constructor.

For more details on the "magic parentheses," I'd recommend reading Michael Burr's excellent answer to the question "Do the parentheses after the type name make a difference with new?" It discusses value initialization when used with new specifically, but for the most part is applicable to value initialization wherever else it can be used.