问题描述
在 C99 中这是合法的:
In C99 this was legal:
void f(size_t sz) {
char arr[sz];
// ...
}
但是,这个 - 动态大小的堆栈数组 - 在 C++ 中已被删除,并且在 C++11 中没有看到返回.
However, this - dynamically sized stack arrays - has been dropped in C++, and not seeing a return in C++11.
AFAIK C++ 考虑到 C 兼容性,所以我想肯定有一些很好的论据不包括这个有用的特性,对吧?
AFAIK C++ was made with C compatibility in mind, so I wondered There must be some very good argument of not including this useful feature, right?
我能想到的只有这个:
- 通过允许需要在堆栈上的更智能的数组大小(临时缓冲区?)来节省内存.
- 更少的智能指针"(或者更糟糕的是,手动引入错误的
delete []
)和缓慢的堆分配. - 与 C99 的兼容性.
- 允许人们轻松地在堆栈上分配太大的数组,从而导致难以调试的堆栈溢出.
- 编译器编写者更复杂.
为了防止这被封闭为主观的";或不具建设性",我正在寻找来自委员会成员的报价或讨论该问题的讨论链接——当然还有加分,以便快速总结.
To prevent this from being closed as "subjective" or "not constructive", I'm looking for quotes from commitee members or links to discussions talking about the matter - with bonus points for a quick SO roundup of course.
与其将其视为小马与仓鼠的讨论,不如将其视为一个历史问题,仅仅是对所考虑的优点和缺点的兴趣(如果有的话).
Rather than seeing this as a Ponies vs Hamsters discussion, see it as a historical question, mere interest in the advantages and disadvantages that were considered (if at all).
编辑:正如 James McNellis 在下面的评论中指出的那样,C++ 存在于 C99 标准化可变长度数组之前.您可能会将我的问题解读为:他们为什么不添加它,也不会添加它?".
EDIT: As James McNellis pointed out in the comments below C++ existed before C99 standardized variable-length arrays. You might read my question then as: "Why didn't and won't they add it?".
推荐答案
我想,是因为 C++ 提供了优越的解决方案:std::vector
和 std::array
T,N>
(C++11);尽管后者本身不是动态的,但它优于原始数组.无论您传递向量或数组的哪个函数,您始终可以知道大小.
I think, it's because C++ provides superior solutions: std::vector<T>
and std::array<T,N>
(C++11); though the latter is not dynamic as such but it's superior to raw arrays. You can always know the size, no matter which function you pass the vector or array.
由于 C 无法提供这些解决方案,C99 提出了可变长度数组 (VLA).它与普通数组有同样的问题:它在传递给函数时衰减为一个指针,并且您不再知道数组的大小.
Since C cannot provide these solutions, C99 came up with Variable Length Array (VLA). It has the same problem as regular arrays: it decays into a pointer on passing it to function, and you no longer know the size of the array.
正如 Florian Weimer 所问的 here at comp.std.c++
如果 C++0x 允许 VLA,那么下面的代码是什么意思?
And as Florian Weimer asked here at comp.std.c++
that if C++0x allows VLA, then what would the following code mean?
int vla[n]; //n is known at runtime!
std::vector<decltype(vla)> v; //what does this mean?
当向量模板的类型参数取决于运行时已知的n
时,编译器如何在编译时实例化向量模板?
How is the compiler going to instantiate the vector template at compile-time when it's type argument depends on n
which is known at runtime?
这篇关于为什么 C++ 不支持堆栈上的动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!