【问题标题】:difference between two syntax new( int[ size ] ) and new int[ size ]两种语法 new( int[ size ] ) 和 new int[ size ] 之间的区别
【发布时间】:2019-04-04 13:00:49
【问题描述】:

此文本运行时没有任何警告或错误

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]);

【问题讨论】:

  • 这只是new的规则

标签: c++


【解决方案1】:

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

这就是警告中的-Wvla 对应的内容。

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

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

Demo

【讨论】:

  • 可以,但仍然不应该。 new 不是函数。
猜你喜欢
  • 2020-09-24
  • 2018-02-25
  • 2018-03-20
  • 2017-10-17
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
相关资源
最近更新 更多