STL within embedded system with very limited memory

I know this is an old thread, but for anyone that's interested, I maintain an STL-like template library for embedded applications. No heap usage at all.

Embedded Template Library (MIT licence) https://www.etlcpp.com


This question is sort of confused and weird. First, let's clear up some misconceptions.

You mention "stack, queue, deque" by name. Well, two of these are not containers. stack and queue are container adapters. See, they don't actually directly store the elements; they simply mediate the interface to them. stack ensures that you can only push, pop, and get the top element. queue ensures that you can only push-back, pop-front, and get the front element (thought it also lets you get the back element).

The container adapters actually take as one of their template parameters the actual container type to use. So you could use a stack with a std::list if you want. I wouldn't necessarily suggest it (depending on your use case), but you could.

The container adapters don't care about memory; it's the containers that they use that allocate memory.

If you're running in such a tightly memory limited system, you're not going to find the standard containers to be terribly friendly. Even if you use allocators to give them fixed-size memory buffers, the only thing those allocators can do to stop the actual container from allocating more memory is to throw an exception.

For example, if you have a vector that needs to work within 2KB of memory, if it has a size of 1KB, and tries to allocate 2.5KB more, the allocator cannot simply return 2KB. It can either return 2.5KB as requested or throw std::bad_alloc. Those are your only two options. There is no way for the allocator to tell the vector that it can get more memory than what it has, but not as much as it wants.

Similarly, the allocator is required to provide new memory, freshly allocated memory that can be copied into. It is not supposed to provide the same spot of memory only with more of it available. Doing so will likely cause problems in some implementations.

Allocators are intended to provide different regions of memory for access; they're not well designed for limiting the size of the container itself.

My suggesting is to track down a copy of EASTL. It's really designed for this sort of thing. The Github repo I linked you to has some bug fixes and so forth, but it's still mostly the same. It's not a bad bit of code. Their STL-like containers provide most of the interface, so they can be mostly drop-in replacements. But they provide special functionality to specifically control memory allocations.