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?
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?
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
).
new int[];
is not legal.
As per the draft standard n3337 § 5.3.4, []
should have an expression for the first dimension, and a constant-expression for each subsequent dimension (if any), as dictated by the grammar:
noptr-new-declarator: [ expression ] attribute-specifier-seqopt noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt
Here, every constant-expression shall be a converted constant expression, as specified in clause 6:
Every constant-expression in a noptr-new-declarator shall be a converted constant expression (5.19) of type std::size_t and shall evaluate to a strictly positive value. The expression in a noptr-new-declarator is implicitly converted to std::size_t.