简体   繁体   中英

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.

Simple answer: Yes

Long answer:

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized

Now, as value initialization from the standard we get:

— if T is a class type (clause 9) with a user-declared 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 non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized; — if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized

int falls on otherwise, so it is zero initialized

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 .

This member function is overloaded the following way

void resize(size_type sz);
void resize(size_type sz, const T& c);

For the first function the effect is

Effects: If sz <= size(), equivalent to calling pop_back() size() - sz times. If size() < sz, appends sz - size() default-inserted elements to the sequence

That is there is used the expression T(). If elements are of the type int then they are zero-initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM