Reputation: 2035
#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,
Please any one can tell me why this is happening? For each insertion, shouldn't the copy constructor be called only once?
Upvotes: 0
Views: 561
Reputation: 263118
Your copy constructor is flawed, you forgot to actually copy the data :)
base(const base& that) : x(that.x)
{
cout << "base copy constructor\n";
}
Also, if you have a modern compiler, you can write a move constructor and learn something new:
base(base&& that) : x(that.x)
{
cout << "base move constructor\n";
}
Upvotes: 3
Reputation: 46607
If v
needs 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::vector
is implementation-dependent, so your code sample will produce different results with different standard library implementations.
Upvotes: 2
Reputation: 47428
calls to push_back()
increase the size of the vector as necessary, which involves copying of vector's contents. Since you already know that it's going to contain five elements, either v.reserve(5);
right before the loop, or use the range constructor:
base obase[5]={4,14,19,24,29};
vector<base> v(obase, obase+5);
Upvotes: 7