Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading