两种语法new(int [size])和new int [size]之间的区别

时间:2019-04-04 03:29:26

标签: c++

此文本运行无任何警告或错误

int* iPtr;
unsigned int size;
cin >> size;
iPtr = new int[size];

此警告返回但可正常运行!!

  

警告:非常数数组的新长度必须在type-id [-Wvla]周围没有括号的情况下指定        iPtr = new(int [size]);

int* iPtr;
unsigned int size;
cin >> size;
iPtr = new(int[size]);

1 个答案:

答案 0 :(得分:0)

发出此特别警告,因为C ++中不允许使用可变长度数组。括号使编译器将int[size]视为可变长度数组。

这是警告中的-Wvla所对应的。

如果您为size指定一个常量值而不是用户指定的值,则可以使用括号。

int main() {
    unsigned int* iPtr;
    constexpr unsigned int size = 10;
    iPtr = new (unsigned int[size]);
}

请参见 Demo

相关问题