Im working on an exercise in C++ but im getting unexpected output I hope someone can explain. The exercise asked that I make a class called rock which has a default constructor, a copy constructor and a destructor all of which announce themselves to cout.
In the main method I am to try and add members of this class to a vector by value:
vector<Rock> byValue;
Rock r1, r2, r3;
byValue.push_back(r1);
byValue.push_back(r2);
byValue.push_back(r3);
cout << "byValue populated\n\n";
The output I expected (and shown in the exercise solutions) is:
Rock()
Rock()
Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
byValue populated
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
However the output I get is:
Rock()
Rock()
Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
~Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
~Rock()
~Rock()
byValue populated
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
Can anyone explain why there seems to be extra calls to the copy constructor and destructor?
When the vector gets resized, the elements have to be moved to their new location.
This is normal.
If you call
before any calls to
push_back, the extra copies should disappear.