为什么复制到的对象必须与从中复制的对象具有相同的 LOW 常量级别
Why the object copied to must have the same LOW level of constant as the object copied from?
我是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;
将更改常量值。
相关文章:
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 如何在向量列表初始化时避免对象复制以及如何延长临时的生存期
- 了解在 C++ 中分配容器时的对象复制
- C++类对象复制构造函数和运算符=
- 复制 elision/RVO 会导致从同一对象复制/移动吗?
- 如何在循环内将大对象复制到omp任务中?
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 将C++对象复制到指向新指针的指针处
- 将一个 OpenCV OutputArrayOfArrays 对象复制到另一个对象
- 选择性地禁用隐式对象复制
- 不能从文件到指针向量的对象复制
- 从派生对象复制构造
- OpenCV Mat对象复制速度更快
- 将子对象复制到父对象
- 为什么普通的 c++ 编译器不优化对象复制?
- C :将一个对象复制到构造函数中的另一个对象
- 使用命名对象复制构造函数
- 不必要的对象复制 - C++ STL
- 如何将一个类的对象复制到另一个类中