Yongqi Zhang Yongqi Zhang - 4 months ago 9
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
p
and
q
. Can
int *q = new() int(10)
be replaced by
int *q; *q = 10
anywhere?
Thanks a lot.

Answer

No. They are far from the same.

This:

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.

This:

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.