为什么我不能在作业的右侧放置指向 const 的指针?
Why can't I put a pointer to const on right hand side of assignment?
为什么我不能把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);
相关文章:
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- std :: allocator_traits ::用const指针构造
- 汇编问题试图使用qobject_cast进行const指针
- C++ 两个具有相互指向 const 指针的对象
- 我想将指向 const 对象的指针放入包含非 const 指针的容器中.我有什么选择
- 传统代码突变const指针.任何合法的原因
- C#等效于C 中的const指针
- 返回指向 const 数据成员和 'auto' 关键字的 const 指针。有点困惑
- 函数返回由const指针向量生成的指针
- 您如何使用成员正确初始化构造的结构,该构件是指向const值的const指针
- 使用 const 指针的 C 样式字符返回不正确的结果
- 有没有办法将 std::stack<pointer> 转换为 std::stack<const 指针>?
- 为什么当 typedef const 指针与额外的 const 一起使用时,编译器不会给出错误?
- 如何将const_cast的const指针向量映射到非常量指针向量
- 什么场景可能需要使用 需要 const 指针指向(非常量常量)数据
- 强制转换 const 指针以使用旧版 C 代码
- const ref 和 const 指针 c++ 之间的区别
- 将 const 传递给接受 const 指针的函数是不正确的
- 指向指针数组的Const指针
- C++Const指针声明