指向 const 对象的指针的指针的合法定义是什么?

What is a legal definition of a pointer to a pointer to a const object?

我从 知道指针 const int** z 应该被读作

Variable z is [a pointer to [a pointer to a const int object]].

以我的拙见,这意味着如果 z=&y 那么 y 应该是指向 const int 对象的指针。但是,以下代码也可以编译:

int x=0;
int const* y=&x;
const int** z=&y;

为什么 int const* 对象,即指向 intconst 指针而不是指向 const int 的指针可以接受为 [=20] 的指向对象=]?

你误解了 const 指的是什么。 const 总是引用它左边的元素 - 除非它是最左边的元素本身,它引用右边的元素。

这意味着 int const * 是一个指向 const int 的指针,而不是你想象的指向 int 的 const 指针。为此,您必须编写 int * const

int const *const int *两种写法完全一样:一个指向const int的指针。

如果您阅读了从 rightleft 的声明,您就明白了。如果const是最左边的元素,读的时候在前面加一个“就是”。例如:

  1. const int *: 指向常量的 int 指针。
  2. int const *: 指向 const int 的指针。
  3. int * const: 指向 int 的 const 指针。
  4. const int * const: 指向 int 的 const 指针,即 const。
  5. int const * const: 指向 const int 的 const 指针。

注意1/2相同,4/5相同。 1 和 4 被称为“west const”,因为 const 在 west/left 一侧,而 2 和 5 被称为“east const”。

Why is an int const* object i.e. a const pointer to an int

没有

int const *const int *是同一类型。

人们有时更喜欢写 int const *,因为它从右到左读作 "指向 const int 的指针",而 const int * 实际上读作“指向 int(常量)的指针”

指向 intconst 指针是 int * const

试一试:

  int a = 42;
  const int * y = &a;
  int const * z = &a;

  *y = 24; // compile error assigning to const
  *z = 24; // compile error assigning to const

  int b = 0;
  y = &b;
  z = &b; // re-pointing non-const pointers is fine
  *z = 1; // still a compile error

  int * const x = &a;
  *x = 24; // fine, assigning via pointer to non-const
  x = &b;  // error reassigning a const pointer