Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack_array in C++ Core Guidelines

Tags:

c++

c++11

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?

like image 479
Zizheng Tai Avatar asked Feb 01 '17 11:02

Zizheng Tai


2 Answers

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.

like image 179
eerorika Avatar answered Nov 04 '22 16:11

eerorika


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.

like image 2
TBBle Avatar answered Nov 04 '22 16:11

TBBle