views:

611

answers:

5

What is the memory overhead of having an empty vector vs having a pointer to a vector?

Option A:

std::vector<int> v;

Option B:

std::vector<int> *v = NULL;

I believe that option B takes 1 32 bit pointer (assuming 32 bit here) How much memory does the empty 'v' take up?

+1  A: 

Implementation dependant, probably a pointer and two integers for current size and capacity.

anon
+3  A: 

std::vector v; takes up sizeof(v) space. It might vary by implementation, so run it and find out how much it takes for you.

Welbog
And what about dynamic memory used internally by the vector?
Diego Sevilla
A default constructed vector has no size and never had any, so it should have no dynamic allocation.
Michael Burr
+5  A: 

Firstly there's no such thing as a "std::vector v". Vector is a template-based collection and thus needs a type. E.g

std::vector<int> v;

Secondly it's completely implementation-dependent and you should neither assume nor rely on the details. For what it's worth it's 20-bytes using VC.

Andrew Grant
the "<int>" was hidden by the browser (interpreted it as html tag)
Johannes Schaub - litb
+4  A: 

As for the question as asked: It depends on the implementation. With MSVC 7.1 this:

std:: cout << sizeof(std::vector<int>) << std::endl;

gives me 16. (3 pointers: begin, end, and end of capacity, plus an allocator)

However it should be noted that the pointer-to-vector has a larger overhead:

  • in both time and space in the non-empty case
  • in complexity in all cases.
Éric Malenfant
ur last point is very good. +1 for that
Johannes Schaub - litb
A: 

VS2005:

std::vector<int> *ptrToVec = new std::vector<int>();
std::vector<int> vecOfInt;

sizeof(ptrToVec) = 4
sizeof(vecOfInt) = 20

Thanks!