views:

312

answers:

4

Recently, after being very tired, I wrote the following code:

GLfloat* array = new GLfloat(x * y * z);

Which, of course should have been:

GLfloat* array = new GLfloat[x * y * z];

(Note the square brackets as opposed to the parenthesis.)

As far as I know, the first form is not valid, but g++ compiled it. Sure, it spat out a completely incomprehensible segfault, but it compiled.

Why?

+15  A: 
GLfloat* array = new GLfloat(x * y * z);

Creates a pointer called array to an object of type GLfloat with a value of x * y * z.

dirkgently
+2  A: 

Well, the first expression is a pointer to a GLfloat with value (x*y*z), which is perfectly legal.

Julian Aubourg
+9  A: 

Well, the result of new T() is a T*, so new GLFloat would return a GLFloat*. As long as x*y*z is valid to pass to the GLFloat constructor, it's valid code.

Charlie
+7  A: 

It's the same sort of thing as:

int * p = new int(42);
anon