Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does zero-sized array allocation do/mean?

Looking at some example code and come across some zero-size array allocation. I created the following code snippet to clarify my question

This is valid code:

class T
{
};

int main(void)
{
  T * ptr = new T[0];

  return 0;
}

What is its use? Is ptr valid? Is this construct portable?

like image 618
dubnde Avatar asked Aug 11 '09 11:08

dubnde


1 Answers

5.3.4 in the C++ Standard:

6 Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value...

7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

So, your code allocates an array which behaves in every respect like any other array of T (can be deleted with delete[], passed as a parameter, probably other things). However, it has no accessible indexes (that is, reading or writing ptr[0] results in undefined behaviour).

In this context the different between the constant-expression and the expression is not whether the actual expression is compile time constant (which obviously 0 is), but whether it specifies the "last" dimension of a multi-dimensional array. The syntax is defined in 5.3.4:1.

like image 146
Steve Jessop Avatar answered Nov 12 '22 12:11

Steve Jessop