Why no variable size array in stack?

后端 未结 7 1135
南方客
南方客 2020-11-27 19:28

I don\'t really understand why I can\'t have a variable size array on the stack, so something like

foo(int n) {
   int a[n];
}

As I underst

相关标签:
7条回答
  • 2020-11-27 19:58

    Simple answer: because it is not defined in the C++ standard.

    Not so simple answer: Because no one propsed something behaving coherently for C++ in that case. From the standards POV there is no stack, it could be implemented totally differently. C99 has VLAs, but they seem to be so complex to implement that gcc only finished the implementation in 4.6. I don't think many people will want to propose something for C++ and see compiler manufacturers struggle with it for many years.

    0 讨论(0)
  • 2020-11-27 19:58

    Stacks are fairly small, and their sizes can vary dramatically per architecture. The problem is that it is fairly easy to 'over-allocate' and cause a seg fault or write over memory owned by somebody else. Meanwhile, solutions to the problem (e.g. vector) have existed for a long time.

    FWIW, I read Stroustrup say that he didn't want them, but I don't know which interview it was in.

    0 讨论(0)
  • 2020-11-27 20:00

    Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard.
    Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable.

    C++ provides std::vector for implementing a similar functionality as VLA.


    There was a proposal to introduce Variable Length Arrays in C++11, but eventually was dropped, because it would need large changes to the type system in C++. The benefit of being able to create small arrays on stack without wasting space or calling constructors for not used elements was considered not significant enough for large changes in C++ type system.

    0 讨论(0)
  • 2020-11-27 20:01

    Because in C++ a static array needs a static constant size, so it is not allowed by the language. Note that C99 does support vararrays at the stack, and some implementations support it under C++ as well as an extension.

    0 讨论(0)
  • 2020-11-27 20:04

    Because the language specification says so. Nothing else matters (and explaining with segments is terribly wrong for different reasons).

    0 讨论(0)
  • 2020-11-27 20:13

    Note that the proposal was rejected and the following is no longer true. It may be revived for a future version of C++ though.

    VLA as described in N3639 has been accepted in Bristol meeting and will become part of C++14, as well as a library counter-part "dynarray". So using compiler with C++14 support we can start writing something like:

    void func(int n)
    {
        int arr[n];
    }
    

    Or use dynarray:

    #include <dynarray>
    
    void func(int n)
    {
        std::dynarray<int> arr(n);
    }
    
    0 讨论(0)
提交回复
热议问题