Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an unused STL container allocate memory?

Given the code:

class Foo {
  std::vector<int> items;
  std::map<int, int> dictionary;
};
  1. 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?)

  2. 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++.)

like image 240
silentorb Avatar asked Feb 24 '16 17:02

silentorb


People also ask

Are STL containers allocated on heap?

std::vector always has its buffer allocated on heap.

Does STL use dynamic memory?

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.

Is STL container thread safe?

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.

What is an STL container?

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.


2 Answers

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

like image 94
knivil Avatar answered Oct 11 '22 03:10

knivil


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.

like image 27
SergeyA Avatar answered Oct 11 '22 05:10

SergeyA