class item {
int i;
};
vector<item> ls(3); // line 1
item i1(1); // line 2
ls.push_back(i1); // line 3
- line 1:
- default ctr called once
- copy ctr gets called 3 times
- line 3:
- copy ctr gets called 4 times
My question is in line-3, what initial 3 copy ctr are doing?
Your Expectation:
You probably expected the default constructor for
itemto be called3times, Instead of the default constructor is being called once and the copy constructor3times.What Actually happens:
It is creating a class
itemobject and then copying it to each element of the vector. There are3elements and hence the3copy constructor calls.Rationale:
One can not make any assumption how the elements are constructed by
std::vector. The standardsays only that there must be a default constructor anddoes not force thestd::vectorimplementation to do anything else in specific in this regard.What Actually happens:
The vector was initially created for
3elements so when you push a4thelement, the first first3elements have to be copied to new locations,so that the vector can accomodate the new element and yet have contigious allocation, this accounts for3copy constructor calls. The methodpush_backcreates a copy of the elelemnt being added and then adds it to the vector, so that results in the4thcopy constructor call, In all this results in4copy constructor calls.