简体   繁体   English

int`* p = new int [5];和int * p = new int [5];之间有什么区别?

[英]What is the difference between int `*p = new int(5);` and `int *p = new int[5];`

I just need to understand what the differences between these are: 我只需要了解它们之间的区别是什么:

int *p = new int[5];

and

int *p = new int(5);

One creates an array of five int s and assigns a pointer to this array's first element to p . 创建一个由五个int的数组,并将指向该数组的第一个元素的指针分配给p None of the integers in this array are initialized: 此数组中的所有整数均未初始化:

int *p = new int[5]; // a pointer to an array of 5 integers

The other one creates a single int , and assigns a pointer to that int to p . 另一个创建单个int ,并将指向该int的指针分配给p This integer is initialized with 5 : 该整数用5初始化:

int *p = new int(5); // a pointer to an int

As tadman points out in his comment, in essence, the difference is between the operator new and operator new[] . 正如塔德曼(Tadman)在其评论中指出的那样,本质上, operator newoperator new[]之间是有区别的。 new[] allocates an array and must be deleted with delete[] , while new allocates a single object and must be deleted with delete . new[]分配一个数组, 必须使用delete[] ,而new分配一个对象,并且必须使用delete If you delete with the wrong operator, what happens is undefined behavior. 如果使用错误的运算符删除,则会发生未定义的行为。 Of course, unless you are a library implementer, you should generally prefer smart pointers and library containers over new and new[] . 当然,除非您是库实现者,否则通常应该首选智能指针和库容器,而不是newnew[]

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

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