Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why constant size of struct despite having a vector of int

Tags:

c++

struct

sizeof

I have defined a struct which contains a vector of integer. Then I insert 10 integers in the vector and check for the size of struct. But I see no difference.

Here is my code:

struct data
{
  vector<int> points;
}

int main()
{
  data d;
  cout << sizeof(d) << endl;
  for (int i=0; i< 10; ++i)
    d.points.push_back(i)
  cout << sizeof(d) << endl;

In both the cases I am getting the same result : 16

Why is it so? Shouldn't the size of struct grow?

like image 584
bhavesh Avatar asked Dec 03 '22 22:12

bhavesh


1 Answers

A vector will store its elements in dynamically allocated memory (on the heap). Internally, this might be represented as:

T* elems;        // Pointer memory.
size_t count;    // Current number of elements.
size_t capacity; // Total number of elements that can be held.

so the sizeof(std::vector) is unaffected by the number of elements it contains as it calculating the sizeof its contained members (in this simple example roughly sizeof(T*) + (2 * sizeof(size_t))).

like image 106
hmjd Avatar answered Feb 20 '23 08:02

hmjd