这是参考重新分配的一个例子吗? C ++ 11 [英] Is this an example of reference reassignment? C++11

查看:179
本文介绍了这是参考重新分配的一个例子吗? C ++ 11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,引用变量一旦被初始化就不能改变。例如,请参阅此问题。然而,这里是一个微型工作示例,它会重新分配它。我误解了什么?为什么该示例打印42和43?

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


推荐答案

重新分配。而是将 q 中的对象复制分配 ref 在您的示例中是 t )。

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).

这也证明你为什么得到42作为输出:默认的副本赋值操作符修改了第一个对象。

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

这篇关于这是参考重新分配的一个例子吗? C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆