I understand that push_back in an std::vector places a copy of the object passed as argument at the end.
Let's consider this simple example
class Foo
{
public:
Foo(int i=-1) :i_(i) {std::cout << "Foo:" << i_ << std::endl;}
Foo(const Foo& rhs)
{
i_ = rhs.i_;
std::cout << "Foo copy CTOR:" << i_ << std::endl;
}
~Foo() {std::cout << "~Foo:" << i_ << std::endl;}
private:
int i_;
};
And this fragment of code
void testObjects()
{
std::vector<Foo> vFoo;
for (int i=0; i < 3; i++)
{
std::cout << std::endl;
Foo aFoo(i+100);
vFoo.push_back(aFoo);
std::cout << "i=" << i << " vector size=" << vFoo.size()
<< std::endl;
}
std::cout << "end of loop - vector size=" << vFoo.size()
<< std::endl << std::endl;
}
The result that I am getting is:
Foo:100
Foo copy CTOR:100
i=0 vector size=1
~Foo:100
Foo:101
Foo copy CTOR:100
Foo copy CTOR:101
~Foo:100
i=1 vector size=2
~Foo:101
Foo:102
Foo copy CTOR:100
Foo copy CTOR:101
Foo copy CTOR:102
~Foo:100
~Foo:101
i=2 vector size=3
~Foo:102
end of loop - vector size=3
~Foo:100
~Foo:101
~Foo:102
I've got the impression the the vector increases its size by one (as expected) and its content is shifted (down ?), causing extra (??) copy-construction. Am I right?
I thank you in advance for your time.
Regards