关于C ++中的int [指向数组的指针]:在C ++标准中是int [指向数组的指针]吗?

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)实现的,两个代码样本都有效这一事实只是一个特定于意外/编译器的事实
  • 它在某个地方是标准化的,并且这种算法的结果在每个平台上都应该是相同的。

假设加法应该是交换的,这是合理的,但是如果我们以这种方式实现operator[],我们已经使其他东西成为交换的,可能不是我们想要的。

有趣的是,没有pointer[pointer]操作符,所以operator[]不是宏。

我知道这很糟糕。我知道这让读代码的人很困惑。但我想知道这是否只是一个意外,在一个遥远的土地上,独角兽有七条腿和角在他们的左脸颊上,它将不起作用。


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 that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. 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 that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an
array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric
appearance, subscripting is a commutative operation. (emphasis is added).

因此,假设a[b]是作为*(a + b)实现的,是正确的,除非它是直接在编译器中实现的,而不是作为宏实现的。


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