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.
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.
On
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
On
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.
Yes, this can be seen from std::vector::resize documentation which says:
And from defaultInsertable:
(emphasis mine)
Note the
T()in the above quoted statement. This means that after the resizefoo.resize(10);, elements offoowill contain value0as they were value initialized.