While trying to experiment with copy construction by ‘pass by value’ and the followed destruction, I tried this code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Rock{
int sz;
public:
Rock():sz(0){cout<< "Default ctor"<<endl;}
~Rock(){cout<< "Dtor"<<endl;}
Rock(const Rock& r){ cout << "Copy ctor" << endl; sz = r.sz;}
Rock& operator=(const Rock& r) {cout << "In assignment op" << endl; sz = r.sz;}
};
int main()
{
vector<Rock> rocks;
Rock a, b, c;
rocks.push_back(a);
rocks.push_back(b);
rocks.push_back(c);
return 0;
}
And got the below output. Up to line 7 everything is fine, however I could not understand what happens from then on. Can someone clarify?
Default ctor
Default ctor
Default ctor
Copy ctor
Copy ctor
Copy ctor // all fine I got it...
Dtor
Copy ctor
Copy ctor
Copy ctor
Dtor
Dtor
Dtor
Dtor
Dtor
Dtor
Dtor
Dtor
Let’s associate the output to the corresponding code lines.
That one you probably figured out yourself. 🙂
Again, you probably figured that out correctly.
Your comment is clearly wrong, because you almost certainly did not associate both constructor calls with this statement 🙂
What happens is that when adding a copy of
a, the vector only allocated enough memory to store that one copy ofa(it would have been allowed to allocate more, though). Therefore it has to allocate a new memory block large enough to hold both copies ofaandb, copy the copy ofait stored in the old memory block over to the new one,copybafter it, and then destroy the original copy ofabefore deallocating the (now no longer needed) original memory block.From the above explanation, you now should be able to guess what happens here.
Note however that if you pushed back yet another element to the vector, it’s quite likely that you’d again get just one copy constructor and no destructor call. That’s because a typical strategy for vectors is to double the allocated memory in each step, thus when pushing back
cit most probably allocated space for 4 objects. Actuallystd::vectoris required to use an exponential strategy (it is not required to use the factor 2, though, and it has been argued that the golden mean is a much better factor).Here the three objects
c,b,a, and then the three objects in the vector are destructed.