为什么复制到的对象必须与从中复制的对象具有相同的 LOW 常量级别

Why the object copied to must have the same LOW level of constant as the object copied from?

本文关键字:对象 复制 LOW 常量 为什么      更新时间:2023-10-16

我是C++新手,正在尝试学习关键字const的概念。

我的问题是为什么复制到(在本例中为 *p)的对象必须与从中复制的对象(本例中为 p3)具有相同的 LOW 级别常量。

我知道它们必须具有相同的低级常量才能使代码有效,但我不明白为什么会这样。

背后的原因是什么?

const int *p2;
const int *const p3 = nullptr;
p2 = p3; //ok
int *p = p3; //error: cannot initialize a variable of type 'int *' with an lvalue of type 'const int *const'.

让我们使用一个接受赋值的虚构编译器。

const int a = 1;
const int *const p3 = &a;
const int *p2 = p3; //ok
int *p = p3; //ok too !
*p = 42;

哎呀!我们只是修改了a,这是const。这是一张前往UBland的单程票。这就是无法隐式删除const限定符的原因。

这个问题

有一个很好的答案。

你的问题是const int *意味着 int 是常数,因此,您不能将其地址提供给指向非 const int 的指针。如果他让你这样做,你就可以改变整数。
*p = 5;将更改常量值。