c++classvectormemory-reallocation

How memory works if vectors inside class array are dynamically push_backed?


Assume that we have following class:

class Test {
public:
   Test() {}
   std::vector<int>& getIntList() {
      return intList;
   }
private:
   std::vector<int> intList;
};

Also, we have following codes inside main function to declare class array:

int main(void) {
   Test* test[20];

   for (int i = 0; i < 20; ++i) {
      test[i] = new Test();
   }
}

In these cases, test objects are instantiated.

Now if I append multiple items in the vector inside each class randomly,

there might exist chances to collide memory address range of each vector inside each class while resizing their memory size.

In this case, is the entire 'test' object copied into other memory area and vector is resized? Or, is vector STL only copied into other memory area and resized while the class references the vector?

Entirely, is not a good idea to code like this?


Solution

  • Consider this example:

    struct foo {
        std::vector<int> x;
        std::vector<int> y;
    };
    

    Now sizeof(foo) is a compile time constant. It does not change when you add elements to the vectors. Also sizeof(std::vector<int>) is constant.

    The size of a foo instance is not increasing when the size() of the vector grows. It is similar to having a dynamic array (only for the sake of the example):

    struct bar {
       int* c_array;
    };
    

    Here, sizeof(bar) is likely to be just sizeof(int*), because it is just a pointer, even though it could point to the first element of a c-style array, or to a single int.