我正在阅读 Scott Meyers 的《Effective 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 也会更新。为什么编译器允许它?
最佳答案
both point to the same memory location rhs gets updated even if it is a const reference in the method.
仅保证不能通过参数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++ - 为什么当对象引用不变时,允许更改作为指向另一个类的指针的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525453/