为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
Why member variable which is a pointer to another class is allowed to be changed when the object reference is constant?
我正在阅读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
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 从另一个指针指向函数的指针
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- 使用 SFINAE 测试是否可以将一个指针类型static_cast到另一个指针类型
- 将指针分配给另一个指针时会发生什么情况?
- 如何保存指针地址,以便另一个指针可以继续处理它
- 隐式指针变量,在自动定义中具有另一个指针变量
- RValue 引用在将其绑定(非指针)对象分配给另一个指针后是否会删除该对象?
- Valgrind:将一个指针分配给另一个指针后丢失字节
- 指针将其复制到另一个指针时的工作方式
- 从指针数组的元素传递地址以设置另一个指针地址
- 正在将指针指向的数据复制到另一个指针中
- C++:无法将指针的矢量分配给另一个指针的矢量
- 删除从另一个指针分配的指针,我应该再次删除另一个指针吗?
- 将一个指向成员函数的指针强制转换为同一类的另一个指针
- 访问指针数组/通过另一个指针并删除数组中的单个元素而不删除第一个指针或整个数组
- 在 C++ 中将一个指针复制到另一个指针