#include <iostream>
#include <vector>
using namespace std;
class base
{
int x;
public:
base(int k){x =k; }
void display()
{
cout<<x<<endl;
}
base(const base&)
{
cout<<"base copy constructor:"<<endl;
}
};
int main()
{
vector<base> v;
base obase[5]={4,14,19,24,29};
for(int i=0; i<5; i++)
{
v.push_back(obase[i]);
}
}
When data is inserted into vector, copy to that data goes to vector using the copy constructor.
When i run this program,
- for the first insertion (i=0), one time copy constructor is called.
- for the second insertion (i=1), two times copy constructor is called
- for the third insertion (i=3), three times copy constructor is called
- for the fourth insertion (i=3), four times copy constructor is called
- for the fifth insertion (i=4), five times copy constructor is called
Please any one can tell me why this is happening? For each insertion, shouldn’t the copy constructor be called only once?
If
vneeds to resize its internal buffer, it will usually allocate a totally fresh memory area, so it needs to copy all the objects that were previously in the vector to the new location. This is done using regular copying, so the copy constructor is invoked.You should call
reserve()on the vector to reserve storage upfront if you can estimate how many elements you are going to need.Note that the resize/growth behaviour of
std::vectoris implementation-dependent, so your code sample will produce different results with different standard library implementations.