C++ “new int(100)”有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13797926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:43:34  来源:igfitidea点击:

What does "new int(100)" do?

c++new-operator

提问by JASON

Possible Duplicate:
is this a variable or function

可能重复:
这是变量还是函数

I mistakenly used something like:

我错误地使用了类似的东西:

int *arr = new int(100);

and it passes compile, but I knew this is wrong. It should be

它通过了编译,但我知道这是错误的。它应该是

int *arr = new int[100];

What does the compiler think it is when I wrote the wrong one?

当我写错了编译器会怎么想?

回答by NPE

The first line allocates a single intand initializes it to 100.Think of the int(100)as a constructor call.

第一行分配一个单个int并将其初始化为100. int(100)视为构造函数调用。

Since this is a scalar allocation, trying to access arr[1]or to free the memory using delete[]would lead to undefined behaviour.

由于这是标量分配,因此尝试访问arr[1]或释放内存delete[]会导致未定义的行为。

回答by Peopleware

Wikipedia new(C++)quote:

维基百科新(C++)引用:

int *p_scalar = new int(5); //allocates an integer, set to 5. (same syntax as constructors)
int *p_array = new int[5];  //allocates an array of 5 adjacent integers. (undefined values)

UPDATE

更新

In the current Wikipedia article newand delete(C++)the example is removed.

在当前的 Wikipedia 文章newdelete(C++) 中,该示例已被删除。

Additionally here's the less intuitive but fully reliable C++ reference for newand new[].

另外这里的直观性较差,但完全可靠的C ++参考newnew[]

回答by avakar

It allocates one object of type intand initialized it to value 100.

它分配一个类型的对象int并将其初始化为 value 100

A lot of people doesn't know that you can pass an initializer to new, there's a particular idiom that should be made more widely known so as to avoid using memset:

很多人不知道你可以将初始化器传递给new,有一个特定的习惯用法应该更广为人知以避免使用memset

new int[100]();

This will allocate an array of intand zero-initialize its elements.

这将分配一个数组int并对其元素进行零初始化。

Also, you shouldn't be using an array version of new. Ever. There's std::vectorfor that purpose.

此外,您不应该使用new. 曾经。有std::vector这个目的。

回答by Philipp

The first one creates a single new integer, initializes it to the value 100 and returns a pointer to it.

第一个创建一个新整数,将其初始化为值 100 并返回指向它的指针。

In C/C++ there is no difference between a pointer to an array and a pointer to a single value (a pointer to an array is in fact just a pointer to its first element). So this is a valid way to create an array with one element.

在 C/C++ 中,指向数组的指针和指向单个值的指针之间没有区别(指向数组的指针实际上只是指向其第一个元素的指针)。因此,这是创建具有一个元素的数组的有效方法。