什么是“new int(100)”,做? [英] What does "new int(100)" do?

查看:117
本文介绍了什么是“new int(100)”,做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是一个变量或函数

使用类似:

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?

推荐答案

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

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

由于这是一个标量分配,试图访问 arr [1] 或使用 delete [] 会导致未定义的行为。

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

这篇关于什么是“new int(100)”,做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆