is int[pointer-to-array] in the C++ - standard?
据我所知,可以编写以下代码:
1 2 3 4 | char *a = new char[50]; for (int i = 0; i < 50; ++i) { i[a] = '5'; } |
它编译。它起作用了。它的作用和
1 2 3 4 | char *a = new char[50]; for (int i = 0; i < 50; ++i) { a[i] = '5'; } |
号
只是因为:
- 默认情况下,
a[b] 是作为宏*(a + b) 实现的,两个代码样本都有效这一事实只是一个特定于意外/编译器的事实 - 它在某个地方是标准化的,并且这种算法的结果在每个平台上都应该是相同的。
假设加法应该是交换的,这是合理的,但是如果我们以这种方式实现
有趣的是,没有
我知道这很糟糕。我知道这让读代码的人很困惑。但我想知道这是否只是一个意外,在一个遥远的土地上,独角兽有七条腿和角在他们的左脸颊上,它将不起作用。
C++标准,第83.4页,注释7(第185页)(强调地雷)。
Except where it has been declared for a class (13.5.5), the subscript operator
[] is interpreted in such a way thatE1[E2] is identical to*((E1)+(E2)) . Because of the conversion rules that apply to+ , ifE1 is an array andE2 an integer, thenE1[E2] refers to theE2 -th member ofE1 . Therefore, despite its asymmetric appearance, subscripting is a commutative operation.
号
下面是C++ 11标准所要说的:
Note: Except where it has been declared for a class (13.5.5), the subscript operator
[] is interpreted in such
a way thatE1[E2] is identical to*((E1)+(E2)) . Because of the conversion rules that apply to +, ifE1 is an
array andE2 an integer, thenE1[E2] refers to theE2 -th member ofE1 . Therefore, despite its asymmetric
appearance, subscripting is a commutative operation. (emphasis is added).
号
因此,假设
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
号
…然后,索引和指针的交换性开始起作用。在本版本中,请参见您的友好邻域C++标准,第5.2.1节:HTTP://www-OpenStdOrg/JTC1/SC22/WG21/DOCS/PoSs/2012/N34.5.PDF