为什么我不能在作业的右侧放置指向 const 的指针?

Why can't I put a pointer to const on right hand side of assignment?

本文关键字:const 指针 不能 作业 为什么      更新时间:2023-10-16

为什么我不能把const int *cp1放在分配的右边?请看这个示例

int x1 = 1;
int x2 = 2;
int *p1 = &x1;
int *p2 = &x2;
const int *cp1 = p1;
p2 = p1;    // Compiles fine
p2 = cp1;   //===> Complilation Error

为什么在指定位置出现错误?毕竟,我并不想这么做改变一个常量值,我只是试图使用一个常量值。

毕竟我并没有试图改变一个常量

不允许从"指向const的指针"隐式转换为"指向非const的指针",因为它可能会改变常量值。考虑下面的代码:

const int x = 1;
const int* cp = &x; // fine
int* p = cp;        // should not be allowed. nor int* p = &x;
*p = 2;             // trying to modify constant (i.e. x) is undefined behaviour

BTW:对于您的示例代码,使用const_cast将是好的,因为cp1实际上指向非const变量(即x1)。

p2 = const_cast<int*>(cp1);