The C++ Core Guidelines mention something called a stack_array
. Its usage looks like:
const int n = 7;
int m = 9;
void f()
{
std::array<int, n> a1;
stack_array<int> a2(m); // A stack-allocated array.
// The number of elements are determined
// at construction and fixed thereafter.
// ...
}
But how can such a class be implemented? How can we dynamically determine the stack size at run time?
As far as I know, stack_array
is a suggestion for a hypothetical class that can not be implemented using standard C++ (as of current standard). Its implementation requires (currently) non-standard compiler specific support, and I doubt such non-standard support even exists yet.
The closest you can get is a macro, that wraps a call to alloca
(a non standard feature, which is supported by many compilers). See roalz's answer for a link to a concrete implementation. I'm not sure if that approach can achieve any safety that is not achievable by VLA (another non standard feature, which is supported by many compilers) - which is not to say that VLA are safe to use.
The Microsoft GSL implementation is still interested in having an implementation of stack_array provided, as of November 2016: https://github.com/Microsoft/GSL/issues/348#issuecomment-260241339
See also https://github.com/isocpp/CppCoreGuidelines/issues/347 and particularly https://github.com/Microsoft/GSL/issues/134 which talks about why it's not easy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With