引用C++中的常量对象/指针
Referencing const objects/pointers in C++
我不太理解C++中如何处理引用:
B objB = B(); // Regular B object
const B &refConstObjB = objB; // Reference to const B object
B* ptrB = new B(); // Regular pointer to B
B* const &refPtrConstB = ptrB; // Reference to const pointer to B
以上所有的编译都很好。但是以下内容没有:
const B* &refConstPtrB = ptrB; // Reference to pointer to const B
考虑到对象和指针都被声明为非常量,为什么我可以将对象作为常量对象引用,但不能对指针执行同样的操作?
请注意:const
引用并不意味着const
对象
它只是指通过该引用只读的对象。因此,无论对象是否为const
,都可以有一个只读引用或指向它的指针
现在,如果你提到的是允许的,你可以说refConstPtrB = pointer_to_some_const_B
,然后通过ptrB
变异该对象,这将违反指针目标的const
。
这个错误的原因是你可以用它在类型系统中放一个洞
const B dontChangeMe;
B* ptrB = new B();
/* This step is NOT legal. */
const B* &refConstPtrB = ptrB;
/* Uh oh! I now have ptrB pointing at dontChangeMe! */
refConstPtrB = &dontChangeMe;
因此,你无法完成你标记的作业。
希望这能有所帮助!
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行