Details on C ++ Vector push_back ()

I am trying to debug a program, and at the same time ran into my understanding of the push_back () function for a C ++ vector.

To illustrate my point, I wrote the following short program:

#include <iostream> #include <vector> #include <cstdlib> using std::cout; using std::endl; using std::vector; class Test { private: int mTestMember; public: Test(int val); Test(const Test&); int GetValue() const; }; Test::Test(int val) { cout << "Constructor\n"; mTestMember = val; } Test::Test(const Test& test) { cout << "Copy Constructor\n"; mTestMember = test.mTestMember; cout << "mTestMember: " << mTestMember << endl; } int main(){ vector<Test> tests; tests.push_back(Test(int(5))); cout<< endl; tests.push_back(Test(int(6))); cout << endl; tests.push_back(Test(int(7))); return(0); } 

and if I compile and run, I get the following output:

 Constructor Copy Constructor mTestMember: 5 Constructor Copy Constructor mTestMember: 6 Copy Constructor mTestMember: 5 Constructor Copy Constructor mTestMember: 7 Copy Constructor mTestMember: 5 Copy Constructor mTestMember: 6 

It seems that in the process of the push_back () function, an object is copied, which is passed as an argument to the push_back () function (which I already knew), and then the rest of the elements that were present in the pre-existing ones are also copied to the new vector, starting from the front.

Do I understand my understanding of the process correctly?

+6
source share
1 answer

std::vector stores its elements in an array. An array always has a fixed size, so if you keep adding elements to std::vector , its base array will eventually fill up. When the array is full and you add another element (via push_back or another member function that adds new elements), it should:

  • Create a new, larger array,
  • Copy or move (*) elements from the old array to the new array,
  • Insert a new element into a new array and
  • Destroy the old array

This process is called redistribution. The correct implementation of std::vector should change the size of the array exponentially. The implementation of Visual C ++ std::vector uses a growth factor of 1.5x; other implementations may use a different growth factor.


(*) C ++ 11 adds support for moving objects.

+9
source

Source: https://habr.com/ru/post/920756/


All Articles