What's the difference in c++ between new int and new (int)?
what's the differe开发者_如何学Pythonnce between
int * num = new (int);
and
int * num = new int;
?
Is there a difference at all?
EDIT thx all. ... which one is the most correct answer?
There isn't a difference in the context of your example (using an int type). However, there is a difference if you need to create objects of compound types, where you need to use parenthesized version. i.e:
int (**fn_ptr_ok) () = new (int (*[10]) ()); // OK
int (**fn_ptr_err) () = new int (*[10]) (); // error
For this particular case, no difference at all. Both are same. Just that first syntax is rarely used, maybe because it looks inconvenient and cryptic, and requires more typing!
There's another difference when you want to create a dynamic array
int n = 2;
int *p = new int[n]; // valid
int *q = new (int[n]); // invalid
The parenthesized version requires a constant size.
In this question's case, the meanings of these two new
s are identical.
Grammatically, the operand of the former form new ()
is type-id,
and the operand of the latter is new-type-id.
As for new-type-id, if (....)
appears at the back of the operand, it is
interpreted as the argument list of the constructor.
That is, If we write new int(1)
, the int
is initialized to 1.
On the other hand, as for type-id, if (....)
appears, it is a part of the type.
For example, when we new
a pointer to a function, we have to use
new( type-id )
form.
For example, as new( int(*)() )
.
(Not really an answer, but I can't put this into a comment)
Its even more complicated because of "placement new": http://codepad.org/pPKt31HZ
#include <stdio.h>
void* operator new( size_t N, int x ) {
return new char[N];
}
int main( void ) {
int x = int();
int* a = new( int() ) int;
}
Here its interesting that gcc accepts this, but not MS/Intel.
精彩评论