I was reading Bjarne Stroustrup’s Programming Principles and Practice Using C++ (second edition). On page 597:
double* p5 = new double[] {0,1,2,3,4};
…; the number of elements can be left out when a set of elements is provided.
I typed the code above into Visual Studio 2022, and I get red underlines saying that "incomplete type is not allowed" (same thing happens when I define p5
as a data member), nevertheless, the code compiles and runs successfully.
May I ask if it is fine to define array in such way? If so, why would Visual Studio show those red underlines…?
>Solution :
May I ask if it is fine to define array in such way?
Yes, starting from C++11 it is valid. From new expression’s documentation:
double* p = new double[]{1,2,3}; // creates an array of type double[3]
This means in your example,
double* p5 = new double[] {0,1,2,3,4};
creates an array of type double[5]
Note
This is p1009r2.