gedamial gedamial - 1 month ago 11x
C++ Question

C++ - Cannot 'new' an array on unknown size in spite of Braced-List initialization?


I've found nothing around about this issue. The only thing I've found is people dynamically allocating an array without providing any information about the size of said array, like this

int* p = new int[];

My issue is different:

float arr[]{ 1,2,3 };
float* p = new float[]{1, 2, 3};

The first line compiles fine, the second one doesn't:

Error C3078 Array size must be specified in new expressions

I wonder: why didn't the compiler evaluate the array size from the list-initialization like it did in the first case?

void* operator new[] (std::size_t size);

requires the size explicitly. You can define your own operator to take the initialiser list.

As a commentator said, std::vector is normally the preferred approach but I guess you are interested in the technicalities of the language, which is why you asked.