+ 1
Could someone explain why this outputs 6?
2 Answers
+ 2
Nice catch. I dug a little and this is what I found out:
- vector<A>v(4,1) allocates memory for a vector of exactly 4 objects, then creates ONE object, which it DOESN'T put into the vector, but instead it makes 4 copies of it and THOSE are put into the vector, THEN it destroys the object it created - count becomes 1;
- when you push_back(), bc it initially allocated memory for exactly 4 elements, it doesn't have room for another one, so it allocates another memory with more space (double perhaps?) for the vector, then creates one object which, again, it DOESN'T put into the vector, but COPIES it, then copies all the other objects from the old location of the vector, then destroys all the objects from the old location - count increases by 4, becoming 5, then it destroys the object it created for the push_back(), count becoming now 6.
To find all these, I modified your code a bit - I added a member to the class, to be able to identify the objects, and a copy constructor that appends a 0 to the member to showcase how many levels it has been copied (one 0 means a first copy, two 0's mean copy of copy and so on; you'll notice that none of the elements of the vector are created directly, all of them are copies), and counted and displayed everytime the constructors and the destructor are called.
https://code.sololearn.com/c4xIi61L5Q8k
+ 1
thanks a lot lion...really good explanation