Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ sizeof Vector is 24?

Tags:

c++

vector

I was just messing around and learning about vectors as well as structs, and at one point, I tried outputting the size of a vector in bytes. Here's the code:

#include <iostream> #include <vector>  struct Foo{     std::vector<int> a; };  int main() {     using std::cout; using std::endl;         Foo* f1 = new Foo;      f1->a.push_back(5);     cout << sizeof(f1->a) << endl;     cout << sizeof(f1->a[0]) << endl;      delete[] f1; } 

The output is 24 and 4.

Obviously the second line printed 4, because that is the size of an int. But why exactly is the other value 24? Does a vector take up 24 bytes of memory? Thanks!

like image 863
Archie Gertsman Avatar asked Dec 01 '15 16:12

Archie Gertsman


People also ask

Can you use sizeof on vector?

The sizeof operator returns the size in bytes of the object or expression at compile time, which is constant for a std::vector .

How many bytes is a vector in C++?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.

What does sizeof vector return?

Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.

How do you find the size of a vector?

To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.


1 Answers

While the public interface of std::vector is defined by the standard, there can be different implementations: in other words, what's under the hood of std::vector can change from implementation to implementation.

Even in the same implementation (for example: the STL implementation that comes with a given version of Visual C++), the internals of std::vector can change from release builds and debug builds.

The 24 size you see can be explained as 3 pointers (each pointer is 8 bytes in size on 64-bit architectures; so you have 3 x 8 = 24 bytes). These pointers can be:

  • begin of vector
  • end of vector
  • end of reserved memory for vector (i.e. vector's capacity)
like image 73
Mr.C64 Avatar answered Sep 22 '22 17:09

Mr.C64