To understand this, you need to understand how the new operator works. new returns a pointer to the beginning of the allocated new allocated memory block. so when we say
int* p = new int;
we allocate memory for one element. But when we talk
int* foo = new [3];
we allocate a block of memory for elements of type int, where "3" is the number of blocks of memory for an integer type. Thus, this tells the compiler to allocate memory for 3 integers. When we do it
int* p = new int[3]{1,2,3}
we ask the compiler to allocate 3 memory cells that will store an integer value. At the same time, we also assign values ββto these memory cells.
Now if we do that
int* p = new int[] {1,2,3}
we donβt tell the compiler how much memory is allocated, but at the same time we are trying to assign 3 memories, but we have not allocated as much memory. In this case, the compiler allocates only 1 block of memory. Thus, the first value is assigned. This will cause a runtime error.
Now the weird thing is that if allowed below, and the compiler is smart enough to assign 3 values
int n[] = {1, 2, 3}
why not in this case
int *p = new int [] {1,2,3}
I think this is a problem with how the new operator is being developed. You can probably try to overload the new operator and solve this problem.
Hope this helps.
EDIT: I tried some dummy code in VS. It seems if you do it
int* p = new int [] {1,2,3}
his accident. But when you do it,
int* p = new int []{1}
it is perfectly. This proves that the compiler interprets it as a command to allocate only one block of memory.