Search code examples
c++arraysmultidimensional-arrayvariable-length-array

Why does operator new can't construct multidimensional array of non-constant size?


I can write operator new for one-dimensional array as follows:

int n{3};
new int[n];

It allocates at least sizeof(int) * n bytes. But when I want to create two and more dimensional array, only first dimension may be non-constant:

int n{3};
new int[n][3]; //ok
new int[n][n]; //error;

Why such restrictions are take place? Are there any difficulties to determine, that it is at least sizeof(int) * n * n bytes to allocate?


Solution

  • The C++ type system does not include arrays with runtime bound. This is a very complicated thing to do, considering that it will have implications for templates and overload resolution. There have been proposals but none has progressed to being accepted for standardization.

    So T[n] is not a valid type. However it can be used in a new-expression because there is a special case for it. The new-expression can be either:

    • new X, where X is a type
    • new T[n], where T is a type and n is not a constant expression.

    Note that both cases are needed because T[n] is not a type but we want to allow that in a new-expression.

    The second point needs a little bit more explanation. It actually uses the C++ infix notation, so if T is an array or function type, the [n] will be in a different place. For example new int[n][3] is OK , which is the same as typedef int T[3]; new T[n]. But new int[3][n] is not.

    If we did allow new int[3][n], what would the return type be? int (*)[n] is not part of the C++ type system as mentioned earlier.