Search code examples
c++vectormemory-management

How can a vector reserve memory for object containing inner vector?


Let say I've an object like this:

struct MyObject
{
    int someId;
    std::vector<int> innerVector;

    MyObject(int a)
    {
        innerVector.reserve(a);
    }
};

and I try to reserve a vector of MyObject this way:

std::vector<MyObject> myObjects;
myObjects.reserve(maxItemsToBeAllowed);

how can it reserve memory if the size of innerVector vector on each MyObject is unpredictable? Does it just "try" and in case of larger innerVector reallocate at runtime?


Solution

  • Remember that the guts of a std::vector are likely stored using dynamic memory allocation, so the base object size is predictable and known in advance.

    All it's doing is reserving N times that footprint when you call reserve(n). Once those entries are used, they'll likely need additional allocation, unless, for example, you just keep them empty.

    In other words, sizeof(std::vector<X>) is predictable. The total memory cost of such a structure is a different thing entirely.

    If, on the other hand, you had std::array<std::array<X>> then it's a whole different story. Those behave a lot more like C arrays.