Search code examples
c++vectorlanguage-lawyerallocation

Is std::vector X(0) guaranteed not to allocate?


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.


Solution

  • 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.