Memory consumption of a pointer to vector of pointers

前端 未结 5 2088
有刺的猬
有刺的猬 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:41

    The memory consumption of the vector is close to what you guessed. You're right that the size of the vector will be independent of the layout of data.

    As for actually calculating the total size of the vector, there are two parts that contribute:

    1. The actual vector object itself. A vector has some internal structure, for example, it has a pointer to it's internal array. Also, all its field are aligned to certain values. The total size of any vector (including the alignment) can be found using sizeof(vector). On my machine this gives 24

    2. The size of the internal array. This is not based on the size() of the vector, but is actually dependent on the capacity() of the vector. The total size will be my_data->capacitiy() * sizeof(data*). I believe there is no padding between array elements, but if there is, this will also have to be accounted for.

    The total memory consumption is then just the sum of #1 and #2.

提交回复
热议问题