为什么当我使用 int 设置数组维度时,必须将数组维度转换为 int?

  • 本文关键字:int 数组 转换 设置 c++
  • 更新时间 :
  • 英文 :


我有一个名为Cells的成员指针,声明为:

Cells* cells;

在成员函数中,我为如下单元格分配一些内存:

void myClass::SetSize(int w, int h)
{
cells = new Cells[w*h]; //gives a warning
}

警告为:C26451 Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow.

我看到一些人断言这是一个VS2019错误,如果是这样的话,那也没关系。但其他人坚持认为这是正确的,我不明白为什么。为什么有必要在这里做石膏?

new表达式接受一个无符号类型的std::size_t。传递int,这是一个有符号的类型,将需要类型转换。根据系统上intstd::size_t的大小,这可能是一个缩小的转换。

最新更新