【问题标题】:Why can't I put a pointer to const on right hand side of assignment?为什么我不能在赋值的右侧放置一个指向 const 的指针?
【发布时间】:2016-12-16 06:58:27
【问题描述】:

为什么我不能将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

为什么我会在指定位置收到错误消息?毕竟我不是想 更改一个常量值,我只是想使用一个常量值。

我在这里错过了什么吗?

【问题讨论】:

  • 您不能直接将其剥离。如果您可以删除它并修改变量,那么 consts 的意义何在。

标签: c++ pointers constants variable-assignment


【解决方案1】:

毕竟我不是想改变一个常数值

不允许从“指向 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

顺便说一句:对于您的示例代码,使用 const_cast 会很好,因为 cp1 实际上指向非常量变量(即x1)。

p2 = const_cast<int*>(cp1);

【讨论】:

  • 很好的解释。基本上你说的是,
  • 如果一个指针想要保持一个对象不变,不要用一个可能改变它的指针指向那个对象。
  • @LaeeqKhan 是的,保持不变。如果你必须这样做,基本上意味着糟糕的设计。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2020-10-06
相关资源
最近更新 更多