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

▼魔方 西西 提交于 2019-12-25 14:45:32

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26818908/is-this-an-example-of-reference-reassignment-c11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!