1

Preface:

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?

gedamial
  • 1,498
  • 1
  • 15
  • 30

4 Answers4

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

T33C
  • 4,341
  • 2
  • 20
  • 42
  • By showing me the implementation of the **new operator**, you have perfectly answered my question ;) – gedamial Jul 01 '16 at 11:25
  • I'm not sure if this is a good justification, though. Even the non-array `operator new` takes a size, and that's automatically determined by the compiler. Why can't the compiler deduce it for OP's case? If it can via the "user-defined-parameters-placement-new" (`operator new[](size_t, ...)`) then it looks like an overlook in the Standard? – peppe Jul 01 '16 at 11:34
3

I think its a perfectly reasonable question, and it just so happens that due to the nature of how the new operator is defined this is a limitation on it.

What follows is really contrived, but could work for you if you really wanted to avoid explicitly stating the size of dynamically allocated arrays:

template<typename T, T ... args>
T* createArray()
{
    return new T[sizeof...(args)]{args...};
}

Then:

int* arr = createArray<int, 1, 2, 3>();
Smeeheey
  • 9,906
  • 23
  • 39
1

I'm reading Bjarne Stroustrup book "Programming...." in the Chapter 17, page 597 Bjarne explicitly says:

double* p5 = new double[] {0,1,2,3,4}

and in paragraph beneath: "... the number of elements can be left out when a set of elements is provided."

So to me seems that this issue is because of bad implementation of compiler, isn't it?

Ante L
  • 34
  • 5
0

It just… doesn't. There isn't syntax for it.

You could find a rationale in there somewhere, that dynamic memory is usually populated by dynamic data of a dynamic length (otherwise, unless only because it's huge, why are you using dynamic allocation?) and that static deduction of the size of the requested space is therefore likely to be an edge case seldom used.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055