<分区>
我看到在 GCC 和 Clang 中有效的代码如下:
size_t size;
cin >> size;
int arr[size];
工作。但是当然这是不可能的,因为它不是常量表达式。那么,这是为什么呢?如果我们这样做,编译器是否会获取动态内存并自动为我们释放它? (顺便说一句,这在 Visual C++ 中无效)
<分区>
我看到在 GCC 和 Clang 中有效的代码如下:
size_t size;
cin >> size;
int arr[size];
工作。但是当然这是不可能的,因为它不是常量表达式。那么,这是为什么呢?如果我们这样做,编译器是否会获取动态内存并自动为我们释放它? (顺便说一句,这在 Visual C++ 中无效)
最佳答案
这就是所谓的 Variable-length array .它不是 C++ 的一部分,但它作为扩展被一些编译器(如 GCC 和 Clang)支持。这就是为什么它在那些编译器上编译得很好,但它不是合法的 C++。在 GCC 上,您可以使用此编译器标志禁用 VLA:
-Werror=vla
根据 GCC documentation :
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits. For example:
FILE * concat_fopen (char *s1, char *s2, char *mode) { char str[strlen (s1) + strlen (s2) + 1]; strcpy (str, s1); strcat (str, s2); return fopen (str, mode); }
关于c++ - 为什么在某些编译器中可以声明一个数组,如 int myarr[noconstant];而不是在其他人身上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224288/