Why the constant size of the structure, despite the presence of an int vector

I defined a structure that contains a vector of the whole. Then I insert 10 integers into the vector and check the size of the structure. But I do not see the 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 cases, I get the same result: 16

Why is that? Should the size of the structure grow?

+4
source share
2 answers

The sizeof operator is a compile-time operation that gives you the size of the data structure used to support the container, not including the size of the stored elements.

Although this may not seem very intuitive at first, think that when using std::vector you use a small amount of local storage (where std::vector ) that supports pointers in another area containing the actual data. When the vector grows, the data block will grow, but the control structure remains the same.

The fact that sizeof will not change during its lifetime is important, as this is the only way to make sure that the compiler can allocate space for points inside data without interfering with other possible members:

 struct data2 { int x; std::vector<int> points; int y; }; 

If the size of the object ( std::vector in this case) was allowed to grow, it will expand over the space allocated for y , breaking any code that may depend on its location:

 data2 d; int *p = &d.y; d.points.push_back(5); // does `p` still point to `&d.y`? or did the vector grow over `y`? 
+7
source

A vector will store its elements in dynamically allocated memory (on the heap). Inside, it can 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. 

therefore, sizeof(std::vector) does not depend on the number of elements contained in it when calculating the sizeof elements contained in it (in this simple example, approximately sizeof(T*) + (2 * sizeof(size_t)) ).

+10
source

Source: https://habr.com/ru/post/1490299/


All Articles