首页 > 解决方案 > 为什么对引用的赋值使用复制赋值运算符?

问题描述

对于以下示例:

#include <iostream>

using namespace std;

class Obj {
    public:
        Obj& operator=(const Obj& o) {
            cout << "Copy assignment operator called" << endl;
            return *this;
        }
};

Obj o;

int update(Obj& o) {
    o = ::o;
}

int main() {
    Obj o2;
    update(o2);
}

我得到结果:

Copy assignment operator called

为什么在将对象分配给引用时使用复制分配?为什么引用没有更新为指向分配的对象?这是惯例问题还是背后有原因?

标签: c++c++11referencecopy-assignment

解决方案


Assigning to a reference assigns to the object the reference refers to, not the reference itself. Thus, your update function is equivalent to:

o2 = ::o;

推荐阅读