I am trying 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]()
}
}
The resize(9) should allocate 9 elements of type _Struct and it works. But every element of type _Struct is not initialized, especially the data element which is another std::vector. I would like it to be initialized to the empty std::vector. Do I have to do that manually? I thought that the resize() method would have called the default constructor of every _Struct element. Thx
Ps. The names of the structs 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 corresponds in the debug view to [0]().
Ps. Forget the [0]().
No it doesn’t call default element constructor.
std::vectornever calls default constructors internally (it does in C++11, but not in earlier versions of the specification).The full signature for
vector::resizelooks as followsI.e. it has a second parameter (with default argument value). That second parameter is then used as a “source” object to initialize new elements by copy-constructor.
In other words, your call to
resizeis actually equivalent tomeaning that it is you who called the default constructor when you supplied that “source” object to
vector::resize, even though you didn’t notice that.Huh? “Not initialized”? I don’t know what that is supposed to mean, considering that in your sample code every new element created by
resizeis perfectly initialized as described above: it is copy-initialized from a_Struct()element you implicitly supplied toresizeas the second argument. Each_Struct::fvaland_Struct::ivalis zero, and each_Struct::datais an empty vector.(In the original C++98
_Struct::fvaland_Struct::ivalwill remain uninitialized, since pre-TC1 C++98 didn’t support value-initialization. But_Struct::datawill be initialized to an empty vector even in the original C++98).Every
_Struct::datavector is already initialized as an empty vector. What made you believe that it isn’t?P.S. Names that begin with
_followed by an uppercase letter are reserved by the implementation. You are not allowed to use them.