Why is new int[n] valid when int array[n] is not?

前端 未结 9 2224
暗喜
暗喜 2020-12-31 02:00

For the following code:

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

I understand that this is invalid syntax and that it is invalid because the c++ sta

9条回答
  •  臣服心动
    2020-12-31 02:38

    That's because the former is allocated on the stack and the latter on the heap.

    When you allocate something on the stack, knowing the size of the object is essential for correctly building it. C99 allows the size to be specified at run time, and this introduces some complications in building and dismantling the aforementioned stack, since you cannot calculate its size at compile time. Machine code must be emitted in order to perform said calculation during the execution of the program. This is probably the main reason why this feature wasn't included in the C++ standard.²

    On the contrary, the heap has no fixed structure, as the name implies. Blocks of any size can be allocated with no particular order, as long as they do not overlap and you have enough (virtual) memory¹. In this case, knowing the size at compile time is not that relevant.

    Also, remember that the stack has a limited size, mostly to detect infinite recursions before they consume all the available memory. Usually the limit is fixed around 1MB, and you rarely reach that. Unless you allocate large objects, which should be placed in the heap.

    As of what you should use, probably a std::vector. But it really depends on what you are trying to do.

    Also note that C++11 has a std::array class, whose size must be known at compile time. C++14 should have introduced std::dynarray, but it was postponed because there is still much work to do concerning compile-time unknown size stack allocation.


    ¹ blocks are usually allocated sequentially for performance reasons, but that's not required.

    ² as pointed out, knowing the size at compile time is not a hard requirement, but it makes things simpler.

提交回复
热议问题