Memory consumption of a pointer to vector of pointers

前端 未结 5 2085
有刺的猬
有刺的猬 2021-01-26 09:28

I am aware that the size of a pointer is fixed (not the size of the data it points to). Now given that, supposing I have a vector of data in global scope and I declare a pointer

5条回答
  •  囚心锁ツ
    2021-01-26 09:50

    Due to "virtual memory" it is not so simple to say how much "RAM" will be used, but we can talk about how much virtual memory will be consumed. And the answer is roughly as you expected, plus a bit more:

    • Number of elements in the vector * size of each (i.e. size of a pointer).
    • Plus some extra "capacity" in the vector that it uses to avoid constant resizing (probably some small constant factor of the size, and you can query it by calling capacity()).
    • Plus the implementation details of the vector, which might be e.g. three pointers (begin, end, begin + capacity).

    If you wanted to express that in C++, you might do something like this:

    sizeof(vector) + my_data.capacity() * sizeof(data*);
    

    Note that this just gives you a rough guess, and ignores more complex pieces like whether more "RAM" is needed to actually do the mapping of the memory you are using in application space, and the behavior of the standard allocator on your system, etc. But as far as C++ and virtual memory are concerned, I think it's a reasonable approximation.

提交回复
热议问题