Re: Initialization of vectors in c++
On Apr 13, 11:10 pm, pauldepst...@att.net wrote:
Experimenting at home with visual c++, I see that int main()
{std::vector<double> vect(5);} creates a vector whose 5 initial
values are all 0. Is this standard or might the five initial values
be different from 0? I'm a bit surprised by this as I would expect
vect to consist of five uninitialized doubles. Why is it that double
x; introduces a double which is uninitialized and yet the above vect
is initialized? Or is this just a matter of the definition of the c++
language which should just be accepted, and can't be derived from some
other principle?
Here you actually called
explicit vector(size_type n, const T& value = T(),
const Allocator& = Allocator());
so the question becomes what T() equals to.
8.5
7
An object whose initializer is an empty set of parentheses, i.e., (),
shall be value-initialized.
5
To zero-initialize an object of type T means:
-- if T is a scalar type (3.9), the object is set to the value of 0
(zero) converted to T;
....
To default-initialize an object of type T means:
-- if T is a non-POD class type (clause 9), the default constructor for
T is called
(and the initialization is ill-formed if T has no accessible default
constructor);
-- if T is an array type, each element is default-initialized;
-- otherwise, the object is zero-initialized.
so with T==int, int() == 0