In real-time applications, e.g. audio programming, you should avoid allocating memory in the heap during callbacks, because execution time is unbounded. Indeed, if your executable has run out of memory, you'll need to wait for the OS to allocate a new chunk, which can take longer than the next callback call. I could store memory on the stack, e.g. using variable-length arrays (VLA) or alloca()
, but if the array is too large you get a stack overflow.
Instead, I was thinking of defining a class with an interface similar to std::vector
, but that internally uses the stack if the size is smaller than a certain threshold
, and the heap otherwise (I prefer a possible unbounded operation to a certain stack overflow). For the heap part I could use an std::vector
or new
/delete
. But what about the stack? VLAs and alloca()
are deallocated when they get out of scope. What alternative could I use?
I could use an std::array<T, threshold>
, but that would waste memory. I expect my threshold
to be in the order of 2048
.