c++ - 为什么当对象引用不变时,允许更改作为指向另一个类的指针的成员变量?

标签 c++ pointers reference operator-overloading constants

我正在阅读 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/

相关文章:

c++ - C++ 中的字符串流

c++ - std::string::operator[] 的结果地址是否指向一个可写的、以 nul 结尾的缓冲区?

c# - 如何将基于文本的编程代码(存储在数据库中)转换为实际的编程代码?

c - 当我将指针递增 1 时,为什么不能访问字符串中的下一个元素?

c++ - System::对 C++ char* 参数的字符串引用

c++ - 有没有办法阻止开发人员使用 std::min、std::max?

c++ - 检查 NULL 值 C++ 的引用

python - 如何在不复制对象的情况下将 var 添加到 Python 列表中?

java - 传递 Java 对象最有效的方法?

c++ - 如何设置指针内存地址?