vendredi 19 avril 2019

Why does assignment to a reference use the copy assignment operator?

For the following example:

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

I get the result:

Copy assignment operator called

Why is a copy assignment used when assigning an object to a reference? Why isn't the reference just updated to point to the assigned object? Is this a matter of convention or is there a reason behind this?

Aucun commentaire:

Enregistrer un commentaire