2
votes

As some opening info, I'm working with Visual Studio 2013 Community. I've noticed a mismatch between what appears to be inside a std::vector, and what is returned from sizeof, and I was wondering if anyone could shed any light on why this is how it is.

If I declare an empty vector:

std::vector<int> v;

then sizeof(v) is 16 bytes.

4 for the ptr to the first element. _MyFirst

4 for the ptr to just after the last element. _MyLast

4 for the capacity int.

4 for the size int.

Which makes sense.. except there is another member ptr in the vector class, to the end of the vector's capacity called _MyEnd.

So why does sizeof(v) not return 20 bytes?!

EDIT: Turns out some of my assertions were wrong :) The answers below pointed me in the right direction... just in case anyone comes across this in future and is puzzled.

The size of 16 was in debug mode, in release sizeof returns 12. The 12 is the 3 pointers, _MyFirst, _MyLast and _MyEnd.

3
No, its not for production code, I'm just curious. I was doing some research into how std::containers allocate memory and how it all works under the hood, and i came across this.Chris
size and one past the end ptr are redundant.juanchopanza
I think the key word is "appears". Please post the declaration, if you have the source code. Which I think is bundled with Visual Studio.Cheers and hth. - Alf
Not so helpful.. could you explain?Chris
Visual Studio indeed "invents" members in the debugger. This happens for specific types where the internal representation doesn't match the logical value.MSalters

3 Answers

0
votes

Add /d1reportSingleClassLayout switch to your compiler arguments to see the layout of the class. STL explains the use of this switch in his video. There was also a blog post about it from Microsoft SDET working on compiler, but I can't find it now.

0
votes

You cannot rely on a std::vector being any particular size. The size can even change between debug and release modes. Typically a vector is implemented with three pointers but it does have to. In this case if you have a 64 bit system your vector could have 2 pointers. One to the data and one to a struct that has the other information in it. If you are going to need the size of the vector for something in your program then you should just use sizeof(std::vector<type>) and not use a "magic" number.

0
votes

There is no capacity and size member of a typical std::vector implementation. It stores a pointer to the beginning, a pointer to one after the last element it's holding and a pointer just past the end of the allocated block. From these 3 pointers it is able to get all the information it needs.

This is true for GCC as well as Visual Studio in Release. In Debug sizeof(std::vector<int>) returns 32, probably to keep track of iterator invalidation but I don't know for sure.