Why is the size of the array allocated by the heap required with initialization of the initialization list?

While i can write

int n[] {1, 2, 3}; 

I can not write

 int *m = new int[] {1, 2, 3}; 

which should be

 int *m = new int[3] {1, 2, 3}; 

What is the reason for this?

+6
source share
2 answers

Remember that the new one is actually an operator in C ++.

This is due to how the new operator is defined; those. The size of the requested memory is explicitly required as an input parameter. Thus, this will not be deduced by the number of members of the initializer list.

0
source

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.

-1
source

Source: https://habr.com/ru/post/988573/


All Articles