c++c++11integerstdvectorvalue-initialization

Does resize on a std::vector<int> set the new elements to zero?


Consider

#include <vector>
int main()
{
    std::vector<int> foo;
    foo.resize(10);
    // are the elements of foo zero?
}

Are the elements of foo all zero? I think they are from C++11 onwards. But would like to know for sure.


Solution

  • Are the elements of foo all zero?

    Yes, this can be seen from std::vector::resize documentation which says:

    If the current size is less than count,

    1. additional default-inserted elements are appended

    And from defaultInsertable:

    By default, this will call placement-new, as by ::new((void*)p) T() (until C++20)std::construct_at(p) (since C++20) (that is, value-initialize the object pointed to by p). If value-initialization is undesirable, for example, if the object is of non-class type and zeroing out is not needed, it can be avoided by providing a custom Allocator::construct.

    (emphasis mine)

    Note the T() in the above quoted statement. This means that after the resize foo.resize(10);, elements of foo will contain value 0 as they were value initialized.