为什么我不能将指向 const int 的指针的值分配给 int 指针?

Why can't I assign value of pointer to const int to a pointer of int?

[注意:我看到另一个问题询问同一本书中的同一部分,但出于不同的原因]
通读了 C++ 入门书并且正在阅读“顶级常量”部分.这里写着:

The distinction between top-level and low-level matters when we copy an object. When we copy an object, top-level consts are ignored
When we copy an object, both objects must have the same low-level const qualification...

我理解这一点,但我继续多次操作书中给出的示例,以加深我对不同场景的理解。下面的代码就是这样一种情况:

int i = 5;
int *p = &i;
const int *const ptr = p;
p = ptr;

我在 运行 程序之前假设第 4 行是合法的。然而,intellisense 反而给我抛出了这个错误:

A value of type "const int *" cannot be assigned to an entity of type "int *"

现在我做了其他事情,例如 *p = *ptr(这是合法的),ptr = p(这显然是非法的)并将对象 i 更改为 const(这将今后要求我更改 p 并满足复制对象必须具有相同低级常量的条件)。在所有情况下,我都明白为什么
但不适用于这种情况。谁能解释一下为什么这是非法的?

首先考虑这个例子:

void foo(const int* p) {
     *x = 1;  // Error ! x is pointer to const
}

int x = 42;
foo(&x);

x 不是 const。然而,在 foo 中,你不能通过 const int* p 修改它的值,因为它是一个指向 const int 的指针。指向 const int 的指针并不意味着指向的 int 实际上是 const。它仅表示:不允许您通过该指针修改 int

编译器不考虑你实际传递的是什么指针,看*x = 1;foo.

里面是不允许的

另一方面,int * 允许将指针修改为 int。现在考虑一下:

 const int x = 42;
 const int* p = &x;
  
 int* p2 = p;  // Error ! why? 
 *p2 = 0;      // <- because of this

如果您被允许将 const int* 分配给 int*,这将在 const 正确性上造成漏洞,因为 int* 确实允许您修改指针对象。

中的顶级const
 const int* const p3 = &x;

指指针本身。您不能修改指针。虽然你可以修改这个:

 const int* p4;
 p4 = &x;