0

As I understand it, one cannot change the reference variable once it has been initialized. See, for instance, this question. However, here is a minmal working example which sort of does reassign it. What am I misunderstanding? Why does the example print both 42 and 43?

#include <iostream>

class T {
    int x;
public:
    T(int xx) : x(xx) {}

    friend std::ostream &operator<<(std::ostream &dst, T &t) {
        dst << t.x;

        return dst;
    }
};

int main() {
    auto t = T(42);
    auto q = T(43);
    auto &ref = t;
    std::cerr << ref << std::endl;
    ref = q;
    std::cerr << ref << std::endl;
    return 0;
}
Community
  • 1
  • 1
alisianoi
  • 2,003
  • 3
  • 31
  • 46

2 Answers2

4

You're not changing the reference here.

You are replacing the object the reference is referring to.

In other words: after the assignment, your t is replaced by q.

ref is still a reference to t.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
3

That does not perform a reference reassignment. Instead, it copy assigns the object in variable q into the object referenced by ref (which is t in your example).

This also justifies why you got 42 as output: the default copy assignment operator modified the first object.

E_net4
  • 27,810
  • 13
  • 101
  • 139