Let us say, we use std::vector<int>
or std::vector<long>
. As the vector grows in size, would the newly allocated elements be initialized to 0 by default, or the programmer needs to 0 them explicitly?
New elements are value-initialised:
[C++11: 23.3.6.3/9]:
void resize(size_type sz);
Effects: Ifsz <= size()
, equivalent toerase(begin() + sz, end());
. Ifsize() < sz
, appendssz - size()
value-initialized elements to the sequence.
For both int
and long
this means 0
:
[C++11: 8.5/7]:
To value-initialize an object of typeT
means:
- if
T
is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor forT
is called (and the initialization is ill-formed ifT
has no accessible default constructor);- if
T
is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, ifT
’s implicitly-declared default constructor is non-trivial, that constructor is called.- if
T
is an array type, then each element is value-initialized;- otherwise, the object is zero-initialized.
An object that is value-initialized is deemed to be constructed and thus subject to provisions of this International Standard applying to “constructed” objects, objects “for which the constructor has completed,” etc., even if no constructor is invoked for the object’s initialization.
Note, though, that this is not talking about the "reserved" space at the end of the vector. This space does not contain any valid elements, zero-initialised or otherwise. This answer and the standard wording talks only about the elements you get when you perform a resize
without specifying an explicit value for your new elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With