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

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

问题描述

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

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".

推荐答案

变长数组(VLA)是不是在C ++允许按C ++标准。结果
许多编译器包括gcc支持它们作为一个编译器扩展,但要注意的是,使用这样的扩展任何code是非便携式是重要的。

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 ::矢量 执行类似的功能< STRONG> 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天全站免登陆