为什么g ++会编译这个?

flu*_*els 0 c++ compiler-construction syntax segmentation-fault

最近,在我累了之后,我写了下面的代码:

GLfloat* array = new GLfloat(x * y * z);
Run Code Online (Sandbox Code Playgroud)

当然应该是:

GLfloat* array = new GLfloat[x * y * z];
Run Code Online (Sandbox Code Playgroud)

(注意方括号而不是括号.)

据我所知,第一种形式无效,但g ++编译了它.当然,它吐出了一个完全不可理解的段错误,但它汇编了.

为什么?

dir*_*tly 15

GLfloat* array = new GLfloat(x * y * z);
Run Code Online (Sandbox Code Playgroud)

创建一个名为array对象的对象,GLfloat其值为x * y * z.


Cha*_*lie 9

好吧,结果new T()是a T*,所以new GLFloat会返回一个GLFloat*.只要x*y*z有效传递给GLFloat构造函数,它就是有效的代码.


小智 7

它与以下类似:

int * p = new int(42);
Run Code Online (Sandbox Code Playgroud)