简体   繁体   English

新int和new(int)之间c ++的区别是什么?

[英]What's the difference in c++ between new int and new (int)?

what's the difference between 有什么区别

int * num = new (int);

and

int * num = new int;

?

Is there a difference at all? 有什么不同吗?

EDIT thx all. 编辑 thx all。 ... which one is the most correct answer? ......哪一个是最正确的答案?

There isn't a difference in the context of your example (using an int type). 您的示例的上下文没有区别(使用int类型)。 However, there is a difference if you need to create objects of compound types, where you need to use parenthesized version. 但是,如果需要创建复合类型的对象,则需要使用带括号的版本。 ie: 即:

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. 在这个问题的案例中,这两个new的含义是相同的。 Grammatically, the operand of the former form new () is type-id, and the operand of the latter is new-type-id. 在语法上,前者new ()的操作数是type-id,后者的操作数是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. 对于new-type-id,if (....)出现在操作数的后面,它被解释为构造函数的参数列表。 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. 也就是说,如果我们编写new int(1) ,则int初始化为1.另一方面,对于type-id,if (....)出现时,它是类型的一部分。 For example, when we new a pointer to a function, we have to use new( type-id ) form. 例如,当我们new一个指向函数的指针时,我们必须使用new( type-id )形式。 For example, as new( int(*)() ) . 例如, 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 由于“放置新”,它更加复杂: 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. 这有趣的是gcc接受了这个,但不是MS / Intel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM