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?
The
sizeof
operator is a compile time operation that gives you the size of the data structure used to maintain the container, not including the size of the stored elements.While this might not seem too intuitive at first, consider that when you use a
std::vector
you are using a small amount of local storage (where thestd::vector
is created) which maintains pointers to a different region holding the actual data. When the vector grows the data block will grow, but the control structure is still the same.The fact that
sizeof
will not change during it's lifetime is important, as it is the only way of making sure that the compiler can allocate space forpoints
insidedata
without interfering with other possible members:If the size of the object (
std::vector
in this case) was allowed to grow it would expand over the space allocated fory
breaking any code that might depend on its location:A
vector
will store its elements in dynamically allocated memory (on the heap). Internally, this might be represented as:so the
sizeof(std::vector)
is unaffected by the number of elements it contains as it calculating thesizeof
its contained members (in this simple example roughlysizeof(T*) + (2 * sizeof(size_t))
).