Given the code:
class Foo {
std::vector<int> items;
std::map<int, int> dictionary;
};
If nothing is ever added to the above vector or map, will either still allocate a block of buffer memory? (In other words, does buffer allocation always happen during container creation or can it be deferred until calls to functions like push_back?)
Is there a standard for handling the timing of initial STL container buffer allocation or is that behavior allowed to vary between STL containers and compilers?
Note: This question is not about the extra bytes such containers would add to the size of class Foo.
(A related subset of this question with an emphasis on allocation size is Initial capacity of vector in C++.)
vector
, and will not pre-allocate anything formap
. – BurmaArrayList
do preallocate. if your array gorws by 2 each time, preallocating 10 elements for example, will save you 4~5 allocations if you starts with 0, then 1,2,4,8,16.. – Humus0, 8, 16, 32, 64
(skip the first small value). No preallocation allows to reserve the right size with only 1 allocation instead of 2. The change of capacity growing add just one test by allocation. – TakingList<T>
. – Graffito