引用C++中的常量对象/指针

Referencing const objects/pointers in C++

本文关键字:对象 指针 常量 C++ 引用      更新时间:2023-10-16

我不太理解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;

因此,你无法完成你标记的作业。

希望这能有所帮助!