alisianoi
alisianoi

Reputation: 2363

Is this an example of reference reassignment? C++11

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;
}

Upvotes: 0

Views: 120

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

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.

Upvotes: 4

E_net4
E_net4

Reputation: 29983

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.

Upvotes: 3

Related Questions