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 the dynamic new int(5)
thing, but here i'm lost. Any clues?
Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.
Dynamic memory allocation is when an executing program requests that the operating system give it a block of main memory. The program then uses this memory for some purpose. Usually the purpose is to add a node to a data structure.
To allocate space dynamically, use the unary operator new, followed by the type being allocated. These statements above are not very useful by themselves, because the allocated spaces have no names!
You are using the comma operator, it evaluates to only one value (the rightmost).
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
Source
The memory address that the pointer is pointing to is initialized with a value of 6 above.
My compiler, g++, returns an error when attempting to do this.
What compiler or code did you see this in?
I believe it is bug which meant to allocate some sort of 2D array. You can't do that in C++ however. The snippet actually compiles because it's utilizing the comma operator, which returns the last expression and ignores the results of all the others. This means that the statement is equivalent to:
int* ptr = new int(6);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With