How do I reserve memory for a std::vector at construction time?

Richard Forrest picture Richard Forrest · Aug 7, 2015 · Viewed 8.2k times · Source

Normally I call reserve on a std::vector immediately after constructing it. Wouldn't this typically cause the std::vector's existing heap allocation to be destroyed and replaced with a new one? Is there a way to reserve the memory at construction time rather than allocate heap space and then immediately destroy it? Or is there an implemenatation trick within the std::vector to ensure this is not an issue?

The available constructors only seem to be able to be useful for filling the std::vector with values, rather than reserving space explicitly.

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Aug 7, 2015

Your question is based on a false premise, namely that a default-constructed std::vector<T> will perform a [zero-length] allocation.

There is literally no reason for it to do so. A fresh vector should have capacity zero (though this is required by sanity, not by the standard).

As such, your goal is already inherently satisfied.

To be blunt, the standard library is not quite that stupid.