C ++: new operator with parentheses "(", ")" instead of brackets "[", "]"

I found a crazy bug in my code.

I wrote the following line:

GLfloat* points = new GLfloat(1024); 

but not

 GLfloat* points = new GLfloat[1024]; 

I just noticed this. My code compiled and ran several times before I noticed an error. I understand that this is an accident, but my question is what does the line that I originally did?

I notice that this is similar to creating a class using a pointer to allocated memory. Does it create one GLfloat on the heap with an initial value of 1024.0 ? If so, why is this a valid syntax? (GLfloat is not a class, is it?)

+5
source share
3 answers

GLfloat is an OpenGL alias for float (i.e. typedef float GLfloat; ). Therefore, the code:

 GLfloat* points = new GLfloat(1024); 

It is equivalent to:

 float* points = new float(1024); 

Assigns a floating-point number and initializes it to 1024.0 and assigns its address to the points pointer.

+4
source

Yes, you create a single GLFloat on a heap initialized to 1024.0. You can initialize primitives with the same syntax as classes. eg.

 int i(10); 

Would create an int on a stack initialized to 10.

+6
source

What does the line that I originally executed did?

  GLfloat* points = new GLfloat(1024); 

Let's try replacing GLfloat with int , you will see that if GLfloat is a type similar to int or float , you will get the following:

 int * points = new int(1024); 

The above statement means that you are creating a pointer to an int with an initial value of 1024 . Thus, in your case, this means creating a points pointer to a variable of type GLfloat and an initial value of 1024 .

This is equivalent to writing the following in the abbreviated version:

 int * points = new int; *points = 1024; 

See here for more details.

+3
source

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


All Articles