Std :: vector push_back () semantics

I understand that push_back in std :: vector puts a copy of the object passed as an argument at the end.

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 piece 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;
}

As a result, I get:

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 got the impression that the vector increases its size by one (as expected), and its contents are shifted (down?), Causing an additional (??) copy. I'm right?

I thank you for your time.

Hello

+4
source share
1 answer

The contents of the vector are not shifted, otherwise push_back()constant time cannot be amortized.

, , std::vector 0 1 , . , , , .

, vFoo:

vFoo.reserve(16);

.

( , 4) , . O (log N) N .

, , std::vector, ++.

+3
source

All Articles