Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector and std::string reallocation strategy

Tags:

c++

gcc

stl

What is the reallocation strategy used for std::string and std::vector in GCC's implementations?

I'm interested in the specific strategy employed: When I append items to a vector (or chars to a string) it may exceed the reserved size and then a reallocation will occur, but what will be the new size as a function of the old one? In case of deleting elements, what is the threshold to actually reallocate and free memory (and again what will be the new size)?

Answers for other compilers will be appreciated as well.

like image 830
Guy Avatar asked Jan 25 '14 15:01

Guy


People also ask

What is the difference between std::string and std::vector?

std::string has a huge number of string-related functions which make it easy to manipulate strings. 2. std::vector, on the other hand, is guaranteed to be contiguous in memory -- that is, &data[x + 1] = &data[x] + sizeof(data[x]). std::string has NO guarantee that it is contiguous in memory.

Does an std::vector allocate on the heap?

As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.

Is std::string movable?

Yes, std::string (since C++11) is able to be moved i.e. it supports move semantics.

How does std::vector allocate memory?

Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required.


1 Answers

Look at the function _M_check_len in bits/stl_vector.h. It contains:

const size_type __len = size() + std::max(size(), __n);

So the basic strategy when you append n elements is either double the size or increase by n, whichever is largest. pop_back never deallocates. libc++ (LLVM) does exactly the same.

Reading the code is the only way you'll find out the strategies for string, deallocation, etc.

like image 115
Marc Glisse Avatar answered Oct 12 '22 20:10

Marc Glisse