Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are newly allocated elements of std::vector<int> initialized to 0?

Tags:

c++

stl

vector

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?

like image 917
MetallicPriest Avatar asked Dec 01 '22 04:12

MetallicPriest


1 Answers

New elements are value-initialised:

[C++11: 23.3.6.3/9]: void resize(size_type sz);

Effects: If sz <= size(), equivalent to erase(begin() + sz, end());. If size() < sz, appends sz - 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 type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T 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, if T’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.

like image 101
Lightness Races in Orbit Avatar answered Dec 04 '22 15:12

Lightness Races in Orbit