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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With