Should std::vectors be used extensively for embedded systems?

Viewed 5883

When writing C++ code for an embedded system with limited CPU and Memory resources, the common rule of thumb is to instantiate objects in the stack, and avoid using the heap unless it is really necessary. Doing this of course has many known benefits, but with the emergence of STL and folks recommending std::vectors as an efficient data structure, does it violate the rule of thumb that I mentioned, since the vector will be using the heap?

Example: In the old days, one would declare static arrays with known sizes that will satisfy the usage. Nowadays, one would just use vectors.

I'm not really comfortable with this transition, since there is always a possibility of the vector failing to allocate the required memory (reminder: this is for embedded systems with limited memory). Using arrays with known sizes in the stack guarantees that there will be space for allocation during compile-time.

Calling reserve() kind of helps, but this is done during run-time.

So, is this a cause for concern, or am I just being paranoid? It's definitely much more easier to use these vectors, but for an embedded environment, it might not be a good idea?

Note: This is not about dynamic vs fixed arrays, but more on how the data is allocated in memory, which is a big deal for my environment. As an example, some folks would do this: Say the array can grow or shrink between 1 to 10 elements. Some folks would create an array that covers this size in the stack, and NULL terminate depending on current size. This way, fragmentation is avoided, and we are guaranteed allocation during compile time. However, switching to vector made it much more cleaner, but at the expense of using the heap, and potentially having to deal with exceptions if allocation fails. This is what I am concerned about.

5 Answers
Related