I was used to using
new int[] {1,2,3,4,5};
for initializing array. But it seems nowadays, this does not work anymore, i have to explicitly state how many elements there are, with
new int[5] {1,2,3,4,5};
so开发者_运维技巧 compilers forgot how to count ?
And to make this a closed question, is there a way to omit the number of elements ?
This has never worked in the current version of C++, you have only been able to zero-initialize (or not initialize) dynamically allocated arrays.
What has always worked is non-dynamically allocated array initialization:
int myarray[] = {1, 2, 3, 4, 5};
Perhaps you are confusing it with this?
Even in C++0x it is not legal syntax to omit the explicit array size specifier in a new expression.
C++ have never allowed to initialize array with an unknown size of elements like above. The only 2 ways I know, is specify the number of elements or use pointers.
With the following test program, test.c++
:
int main() {
int * array = new int[8] { 1, 3, 2, 4, 5, 7, 6, 8 };
int * brray = new int[] { 1, 3, 2, 4, 5 };
return 0;
}
Either syntax from OP is fine if the right C++ standard is used:
$ g++ --version
Apple clang version 12.0.0 (clang-1200.0.32.29)
$ g++ -std=c++03 test.c++ ; echo $?
test.c++:2:26: error: expected ';' at end of declaration
int * array = new int[8] { 1, 3, 2, 4, 5, 7, 6, 8 };
^
test.c++:3:23: error: array size must be specified in new expression with no initializer
int * brray = new int[] { 1, 3, 2, 4, 5 };
~~~^~
2 errors generated.
1
$ g++ -std=c++11 test.c++ ; echo $?
0
This was tested with g++ (which is clang under the hood) from a recent Xcode on macOS.
To summarize: both are available in C++11 standard, but not in the earlier C++03 standard.
is there a way to omit the number of elements ?
Starting from C++11 yes there is a way. This was proposed in p1009r2.
From new expression's documentation:
double* p = new double[]{1,2,3}; // creates an array of type double[3]
This means that the following is valid with modern C++:
int *p = new int[] {1,2,3,4,5}; //valid for C++11(& onwards)
The above statement creates an array of type int[5]
.
Demo
精彩评论