Yongqi Zhang Yongqi Zhang - 1 year ago 40
C++ Question

what is the different between 'new()' int and 'int *p'

As the following codes:

int *p;
*p = 10;
int *q = new() int(10);

I want to know the differences between
. Can
int *q = new() int(10)
be replaced by
int *q; *q = 10
Thanks a lot.

Answer Source

No. They are far from the same.


int *p; *p = 10;

Declares a (uninitialized) pointer to int named p. Then assignes the value 10 to what p points to. This is " undefined behaviour" since p is uninitialized.


int *q = new() int(10);

Declares a int pointer q and initializes it to point to the storage allocated by new which has allocated space for 10 int's (disregarding "()" after new).

To summarize: both - as written - are invalid, broken code, but not the same.

Note: new(...) is "placement new" which is not what you want here.