What does this dynamic allocation do?

Today I found out that you can write such code in C ++ and compile it:

int* ptr = new int(5, 6); 

What is the purpose of this? I know, of course, a dynamic thing, but here I am lost. Any clues?

+6
c ++ new-operator comma-operator dynamic-memory-allocation
source share
5 answers

You use a comma operator, it evaluates only one value (the rightmost one).

The comma operator (,) is used to separate two or more expressions that are included in only one expression expected. When a set of expressions must be evaluated for a value, only the rightmost expression is considered.

A source

The memory address pointed to by the pointer is initialized to a value higher than 6.

+13
source share

My g ++ compiler returns an error when trying to do this.

What compiler or code did you see in it?

+1
source share

I believe this is a mistake that means allocating a kind of 2D array. However, you cannot do this in C ++. The fragment is actually compiled because it uses a comma operator, which returns the last expression and ignores the results of all the others. This means that the operator is equivalent to:

 int* ptr = new int(6); 
+1
source share

5 is ignored. this allocates an int on the heap and initializes it (5,6).

the result of a set of statements separated by a comma operator is the value of the last statement, so int is initialized to 6

+1
source share

Just do the following:

 int* ptr = new int(6); 

As for the comma operator, use it when you cannot perform the desired task without it. No tricks to use, for example:

 int* ptr = new int(5, 6); 
+1
source share

All Articles