Does vector.resize () method call default element constructors when resizing?

I am trying to execute the following code:

struct _Struct2 { void *ptr; double dval; }; struct _Struct { float fval; int ival; std::vector<_Struct2> data; }; std::vector<_Struct> vec; int main() { vec.resize( 9 ); for ( int i = 0; i < vec.size(); i++ ) { _Struct &elem = vec[i]; int len = elem.data.size(); // elem.data is [0]() } } 

Size (9) should highlight 9 elements of type _Struct. And actually it works. But every element of type _Struct is not initialized, especially a data element, which is another std :: vector. I would like it to be initialized with an empty std :: vector. Need to do it manually? I thought that the resize () method would name the default constructor for each _Struct element. thanks

Ps. The names of the structures that are used here are just the first things that come to my mind. This is just an example. My Visual Studio tells me that elem.data in the debug view corresponds to [0]() .

Ps. Forget [0]() .

+6
source share
1 answer

No, it does not call the default element constructor. std::vector never calls internal default constructors (this is done in C ++ 11, but not in earlier versions of the specification).

The full signature for vector::resize as follows

 void resize(size_type sz, T c = T()); 

those. it has a second parameter (with a default argument value). This second parameter is then used as the "source" object to initialize new elements using the copy-constructor method.

In other words, your resize call is actually equivalent

 vec.resize( 9, _Struct() ); 

means that you called the default constructor when you provided this "source" object in vector::resize , although you didn't notice it.

But every element of type _Struct is not initialized, especially a data element, which is another std :: vector.

A? Not initialized? I don’t know what this means, given that in your code example, each new element created by resize is perfectly initialized, as described above: it is initialized by a copy from the _Struct() element, which you implicitly supply to resize as the second argument. Each _Struct::fval and _Struct::ival is zero, and each _Struct::data is an empty vector.

(In the original C ++ 98, _Struct::fval and _Struct::ival will remain uninitialized because pre-TC1 C ++ 98 does not support initialization initialization. But _Struct::data will be initialized with an even even vector in the original C ++ 98).

I would like it to be initialized with an empty std :: vector.

Each _Struct::data vector is already initialized as an empty vector. What made you believe that this is not so?

PS Names starting with _ followed by an uppercase letter are reserved by the implementation. You cannot use them.

+16
source

Source: https://habr.com/ru/post/897304/


All Articles