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++.)
std::vector always has its buffer allocated on heap.
As you know that STL containers such as std::vector, std::deque, etc. allocate memory dynamically internally. They allow you to use your own memory allocator object, but as is often the case we use the default one the std::allocator.
The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.
An STL container is a collection of objects of the same type (the elements). Container owns the elements. Creation and destruction is controlled by the container.
C++ Reference With C++17 the default constructor is noexcept
iff the allocator construction is noexcept
. So it depends on the used allocator. In VS 2015 the standard constructor is noexcept
.
Clarification: It means that if the allocator is no noexcept
then no block of memory is allocated.
And for your second question: Same reference, its is O(1).
Standard doesn't say anything about it, but the implementation I've looked specifically at will do some pre-alocations for std::vector
, and will not pre-allocate anything for std::map
.
This actually once hit me prety hard, when I hade a huge container, which elements had a miniscule - no more than 10 elements, most entries had 0-sized vectors - vector in it. Default vector capacity in this implementation was 32, and '32 * sizeof(vector_element) * number_of_elements' happened to be extremely big.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With