The correct answer was actually provided in this thread, so I just want to provide it with more context.
You need to create your own distributor that uses the alloca() function (or _alloca() on Windows) to dynamically allocate the stack. It is very easy to create it, you can use a typical template distributor scheme, change the allocate () function for the return (pointer)(alloca(size * sizeof(T))); function return (pointer)(alloca(size * sizeof(T))); and make the deallocate() function empty, because there is no manual stack release. After that, you can provide a dispenser to standard containers, for example. vector<T, stack_allocator<T>> .
However, there are two caveats. The allocated stack size can vary significantly, often you have the option to set it at compile time. Visual Studio in 32-bit applications, in my opinion, limits it to 1 MB by default. Other compilers may have different restrictions. There is no problem in 64-bit applications, since the stack can be the size of a heap. You will probably have to catch a structured exception when the stack overflows and convert it to a C ++ exception.
In the second caution, you should never copy stack pointers outside of your function, so moving semantics, for example, will not work if you pass the stack to selected objects in / out of the function.
And there is also one inconvenience, you cannot copy containers with incompatible dispensers, but you can copy them by elements. For example.
vector<int> vint; vector<int, static_allocator<int>> vsint; vint = vsint;
Gene bushuyev
source share