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`?
source share