Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::list, std::vector methods and malloc()

Tags:

c++

stl

Working with stl:list and stl::vector types under interrupt handlers I want to avoid malloc() calls.

The question: What is a best way to prevent malloc() calls in STL list and vector? Is it enough to create structure with predefined size and then avoid push/pop/erase calls?

Thank you in advance

like image 489
BaruchLi Avatar asked Nov 27 '22 06:11

BaruchLi


2 Answers

STL containers like std::list and std::vector have constructors accepting an Allocator type. By supplying your own allocator instead of using the default you are able to control how the container allocates memory. This option is rarely used, but using your own allocator in a real time environment is a good example of where this feature is useful (and proves that the designers of STL did a very good job).

The requirements for you custom allocator type is described in 20.1.6 in the C++ standard

like image 140
Martin Liversage Avatar answered Dec 05 '22 11:12

Martin Liversage


It sounds like you want to preallocate memory in your initialization code, so that your interrupt handler can avoid heap allocations. I'll assume that the elements you're storing in these containers do not themselves perform any heap allocations, because that would complicate the answer.

You can preallocate memory for std::vector by calling the reserve() method. Methods like push_back(), pop(), insert(), and erase() manipulate the vector's size (the number of elements it currently contains). They only affect the capacity (the number of elements it has room for) when the new size is larger than the current capacity. reserve(x) ensures that the capacity is greater or equal to x, increasing the capacity if necessary. (Also note that the only operation that ever decreases a vector's capacity is swap(), so you don't have to worry about erase() reducing the vector's capacity.)

This approach won't work for std::list, but there's another approach that will: preallocate list elements by inserting them into a "spare" list. Instead of inserting new elements, use the splice() method to move them from the "spare" list to the "primary" list. Instead of erasing elements, use the splice() method to move them from the "primary" list to the "spare" list.

like image 24
bk1e Avatar answered Dec 05 '22 09:12

bk1e