为什么零长度数组只被允许,如果是堆分配? [英] Why is zero-length array allowed only if it's heap allocated?

查看:117
本文介绍了为什么零长度数组只被允许,如果是堆分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,它不允许创建零长度的非堆分配的数组。

I notice that it's not allowed to create non-heap allocated arrays of zero length.

// error: cannot allocate an array of constant length zero
char a[0];

我也注意到,它允许创建零长度堆分配的数组。

I also notice that it's allowed to create heap allocated arrays of zero length.

// this is okay though
char *pa = new char[0];

我想他们都是由标准(我没有手头标准的复印件)保证。如果是这样,他们为什么如此不同?为什么不干脆让堆栈(反之亦然)长度为零的数组?

I guess they're both guaranteed by the Standard (I don't have a copy of the Standard at hand). If so, why are they so different? Why not just allow a zero-length array on stack (or vice versa)?

推荐答案

一个0长度数组是不是非常有用。当你计算
维,它可以发生,并且不必治疗的情况下是有用
特别是在你的code。外面的,数组的维
必须是常量,而不是一个计算值,如果你知道
不变的是0,为什么界定呢?

A 0 length array isn't very useful. When you're calculating the dimension, it can occur, and it is useful to not have to treat the case specially in your code. Outside of new, the dimension of the array must be a constant, not a calculated value, and if you know that the constant is 0, why define it?

至少,这是我听说过的理由(从谁工作的人
它)。我不完全相信:它的不寻常的code到有
用符号常量,其值是不知道(从头部工作
文件,或甚至在命令行)。因此,它很可能是有意义的
允许0元素的数组。并且,在过去的至少一个编译器有
让他们,虽然我已经忘了。

At least, that's the rationale I've heard (from people who worked on it). I'm not totally convinced: it's not unusual in code to have to work with symbolic constants whose value isn't known (from a header file, or even the command line). So it probably would make sense to allows arrays of 0 elements. And at least one compiler in the past has allowed them, although I've forgotten which.

在C ++中一个常见的​​技巧是在编译时使用这样的阵列
断言,是这样的:

One frequent trick in C++ is to use such an array in a compile time assert, something like:

char dummyToTestSomeSpecificCondition[ condition ];

这将无法编译,如果条件是假的,并将汇编如果
事实并非如此。除了一个编译器(如果它仍然存在);我将使用
是这样的:

This will fail to compile if the condition is false, and will compile if it isn't. Except for that one compiler (if it still exists); I'll use something like:

char dummyToTestSomeSpecificCondition[ 2 * condition - 1 ];

,以防万一。

这篇关于为什么零长度数组只被允许,如果是堆分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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