Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "new int[];" do?

What does this line of code do?

new int[];

According to my compiler's disassembly (VC++ 2012), it does the same as:

new int[0];

But is it specified by the C++ standard? And is it a legal instruction?

like image 823
NPS Avatar asked Dec 07 '22 00:12

NPS


1 Answers

The expression new int[] is not valid with C++11 (I have not checked C++14).

With a single [] the syntax requires an (implicitly convertible to) integral type expression between the brackets, denoting the desired array size.

Note that this size needs not be a constant: at the bottom level of abstraction this is how you allocate a dynamic array in C++.


C++11 (via the N3290 final draft) §5.3.4/6:

Every constant-expression in a noptr-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a noptr-new-declarator shall be of integral type, unscoped enumeration type, or a class type for which a single non-explicit conversion function to integral or unscoped enumeration type exists (12.3)

expression is used for the first [] brackets. In subsequent [] brackets one must use a constant-expression (value known at compile time) because addressing of the outermost array dimension requires known size array items.


Of course, instead of using new directly you will generally be better off using a std::vector (or maybe std::string).

like image 189
Cheers and hth. - Alf Avatar answered Dec 27 '22 13:12

Cheers and hth. - Alf