为什么堆栈中没有可变大小的数组? [英] Why no variable size array in stack?

查看:31
本文介绍了为什么堆栈中没有可变大小的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白为什么我不能在堆栈上有一个可变大小的数组,所以像

I don't really understand why I can't have a variable size array on the stack, so something like

foo(int n) {
   int a[n];
}

据我所知,部分数据段的堆栈(-segment),因此它不是恒定大小".

As I understand the stack(-segment) of part of the data-segment and thus it is not of "constant size".

推荐答案

根据 C++ 标准,C++ 中不允许使用可变长度数组 (VLA).
包括 gcc 在内的许多编译器都支持它们作为编译器扩展,但需要注意的是,使用这种扩展的任何代码都是不可移植的.

Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard.
Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable.

C++ 提供了 std::vector 来实现与 <强>VLA.

有一个提案 在 C++11 中引入可变长度数组,但最终被放弃,因为它需要对 C++ 中的类型系统进行大量更改.能够在堆栈上创建小数组而不浪费空间或为未使用的元素调用构造函数的好处被认为对于 C++ 类型系统的大更改来说不够重要.

There was a proposal to introduce Variable Length Arrays in C++11, but eventually was dropped, because it would need large changes to the type system in C++. The benefit of being able to create small arrays on stack without wasting space or calling constructors for not used elements was considered not significant enough for large changes in C++ type system.

这篇关于为什么堆栈中没有可变大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆