Rachel Casey
Rachel Casey

Reputation: 225

Regarding Vector Memory Storage

I am learning how vectors work in c++, and wrote a sample program to try to learn how memory with vectors are handled.

#include <iostream>
#include <vector>

int main()
{

//Test 1:
double n = 3.5;
std::vector<double> test;
std::cout <<  sizeof(test) << std::endl;
test.push_back(n);    
std::cout << sizeof(test) << std::endl;

std::cout << std::endl;
   std::cout << std::endl;
      std::cout << std::endl;

//Test 2


std::vector<int> test2;
std::cout << sizeof(test2) << std::endl;
for (int i = 0; i < 1000; i++) {

 test2.push_back(i);   

}

 std::cout << sizeof(test2) << std::endl;
}

Interestingly, the program prints out 24 as the number of bytes stored each-time. Despite adding new elements to the vector. How is the amount of memory that the vector occupies when it is initially declared the same as after I have added elements to the vector?

Upvotes: 0

Views: 77

Answers (1)

Barmar
Barmar

Reputation: 781004

Internally, the vector object has a pointer to dynamically-allocated memory that contains the elements. When you use sizeof(test) you're just getting the size of the structure that contains the pointer, the size of the memory that it points to is not included.

This memory has to be dynamically-allocated so that the vector can grow and shrink as needed. It's not possible for a class object to change its size.

To get the amount of memory being used by the data storage, use sizeof(double) * test.capacity().

Upvotes: 3

Related Questions