Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sizeof a std::pair different to the sum of the sizeof its elements? [duplicate]

Tags:

c++

sizeof

I was trying to create a pair type using dynamic memory and then return it's address to the calling function, but on checking the size of the pair object I got confused:

pair<int,vector<int> > vec;                          //not dynamic definition
vec=make_pair(3,vector<int> {1,2,3,4,5,8,9,0,6});    //9 element in vector
cout<<sizeof(vec.second)<<endl;

OUTPUT: 24

and on doing: sizeof(vec) the output is 32, size of int on my system is 4.

Can someone please explain how the size of 9 ints is 24 and after adding the first member of the pair it becomes 32?

like image 307
Agrudge Amicus Avatar asked Oct 23 '25 01:10

Agrudge Amicus


1 Answers

Despite the vector being called a "container", which it is from a logical perspective, from the perspective of the compiler the vector is just a (template) class which contains a pointer (or maybe several, depending on the implementation) to dynamically allocated memory and probably some other data members that are used for management of this memory. The vector class uses the dynamically allocated memory to expand and shrink, as needed.

Therefore, when using the sizeof operator on the actual vector, you only get the size of the data members that are used for vector management and not the size of the data the vector logically "contains".

Other "container" classes with fixed length, such as std::array or std::pair, are probably implemented without pointers to dynamically allocated memory, so using the sizeof operator on them will probably work as you intended. However, this is implementation-specific and cannot be relied upon.

The reason why the first element of the pair appears to take 8 bytes instead of 4 is probably an alignment issue. The first element contains a 4-byte member whereas the vector likely contains at least one 8-byte member (probably a 64-bit pointer).

like image 59
Andreas Wenzel Avatar answered Oct 24 '25 17:10

Andreas Wenzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!