class A
{
public:
A():a(0)
{}
A(int x):a(x)
{
cout<<"convert"<<endl;
}
A(const A& rhs):a(rhs.a)
{
cout<<"copy: "<<a<<endl;
}
void print()
{
cout<<a<<endl;
}
void Set(int x)
{
a=x;
}
private:
int a;
};
int main()
{
vector<A>vec2(2,A(100));
cout<<"the size: "<<vec2.size()<<" the capacity: "<<vec2.capacity()<<endl;
vec2.push_back(17);
for(int i=0; i<vec2.capacity();i++)
{
vec2[i].print();
}
cout<<"the size: "<<vec2.size()<<" the capacity: "<<vec2.capacity()<<endl;
}
convert copy: 100 copy: 100 the size: 2 the capacity: 2 convert copy: 17 copy: 100 copy: 100 100 100 17 0
why this happened
copy: 17
copy: 100
copy: 100
it seems like the capacity is 5 not 4, and the capacity increased after the element i want to push pushed into the vector, i must be wrong, can someone tell me more details?
If you understand the difference between size and capacity of a vector, you’ll realise that when the capacity needs to be increased the whole vector needs to be moved elsewhere in memory.
The calls to the copy constructor occur when the vector elements get ‘moved’ from the old vector to the new one. If you add a destructor with some debug, it may make more sense to you.
Also…
… is not a good idea. You’re accessing beyond the end of the valid vector data.