gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:04 30 4
gpt4 key购买 nike

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

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

这个返回警告但工作正常为什么!!

warning: non-constant array new length must be specified without parentheses around the type-id [-Wvla] iPtr = new (int[ size ]) ;

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

最佳答案

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

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

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

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

参见 Demo

关于c++ - 两种语法 new( int[ size ] ) 和 new int[ size ] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507404/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com