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

前端 未结 9 2230
暗喜
暗喜 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:49

    The one and only valid answer to your question is, because the standard says so.

    In contrast to C99, C++ never bothered to specify variable length arrays (VLAs), so the only way to get variably sized arrays is using dynamic allocation, with malloc, new or some other memory-manager.

    In fairness to C++, having runtime-sized stack-allocations slightly complicates stack-unwinding, which would also make exception-handling for the functions using the feature consequently more bothersome.

    Anyway, even if your compiler provides that C99-feature as an extension, it's a good idea to always keep a really tight rein on your stack-usage:
    There is no way to recover from blowing the stack-limit, and the error-case is simply left Undefined Behavior for a reason.

    The easiest way to simulate VLAs in C++, though without the performance-benefit of avoiding dynamic allocation (and the danger of blowing the limit):

    unique_ptr array{new T[n]};
    

提交回复
热议问题