CPPL
CPPL

Reputation: 816

Initialize array on the heap without specifying its length

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...?

Upvotes: 2

Views: 358

Answers (2)

user12002570
user12002570

Reputation: 1

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].

Demo


Note

This was proposed in p1009r2.

Upvotes: 1

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12332

If it has to be on the heap then use

std::vector<double> v{0, 1, 2, 3, 4};

if it can be on the stack then use

std::array a{0., 1., 2., 3., 4.}; // all elements must have the right type
std::array b(std::to_array<double>({1, 2, 3})); // when conversion is easier than typing fully typed objects

Upvotes: 0

Related Questions