为什么对引用的赋值使用复制赋值运算符?

问题描述 投票:-2回答:1

对于以下示例:

#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++11 reference copy-assignment
1个回答
1
投票

分配给引用会为引用引用的对象分配,而不是引用本身。因此,你的update函数相当于:

o2 = ::o;
© www.soinside.com 2019 - 2024. All rights reserved.