为什么在对象引用恒定时允许更改为另一个类的指针的成员变量

Why member variable which is a pointer to another class is allowed to be changed when the object reference is constant?

本文关键字:另一个 指针 变量 成员 许更改 对象引用 定时 为什么      更新时间:2023-10-16

我正在阅读Scott Meyers的有效C ,并在项目11中描述了自我分配作者的陷阱,使用了以下代码

class Bitmap { ... };
class Widget {
...
private:
Bitmap *pb; // ptr to a heap-allocated object
};
Widget&
Widget::operator=(const Widget& rhs) // unsafe impl. of operator=
{
delete pb; // stop using current bitmap
pb = new Bitmap(*rhs.pb); // start using a copy of rhs’s bitmap
return *this; // see Item 10
}

因此,当呼叫者的位图指针和过载参数引用(RHS(都指向同一内存位置,即使是该方法中的const引用,也会更新RHS。编译器为什么允许它?

两者都指向同一内存位置RHS即使是方法中的const引用。

只能保证您不能通过参数rhs修改对象。编译器不能阻止您通过其他路线修改。例如

int a = 0;
const int& ra = a; // a can't be changed via ra
a = 42;            // but the original object is still modifiable