3

In theory, given:

std::vector X(0);

Then X will allocate memory from the stack for itself, but is it guaranteed not to allocate heap memory?

In other words, since implementations will generally use a pointer for the vector, is this pointer always initially 0?

Note: this is not the same as Initial capacity of vector in C++ since that asks about capacity when no argument is passed to the constructor, not about guarantees on heap allocations when capacity is 0; The fact that capacity can be non-zero in this case illustrates the difference.

Community
  • 1
  • 1
Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80
  • 2
    Possible duplicate of [Initial capacity of vector in C++](http://stackoverflow.com/questions/12271017/initial-capacity-of-vector-in-c) – Rama May 16 '17 at 13:24

1 Answers1

3

That constructor calls explicit vector( size_type count ) which does:

Constructs the container with count default-inserted instances of T. No copies are made.

The only guarantee you get is that the vector will be empty, its size() will be 0. Implementations are allowed to allocate whatever they want for book keeping or whatever on initialization.

So if your question is if you can count on X taking up 0 bytes of free store space then the answer is no.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • A notable exception I've had in practice is the Debug implementation of MSVC's Standard library (for debugging info I assume). We've had default constructed vectors in the implementation of objects that relied on an allocator that was set only later - before they were actually used, so it was safe in theory - but would fail to find the allocator directly on construction. – KABoissonneault May 16 '17 at 13:42