Why must the copy assignment operator return a reference/const reference?

A bit of clarification as to why it’s preferable to return by reference for operator= versus return by value — as the chain a = b = c will work fine if a value is returned.

If you return a reference, minimal work is done. The values from one object are copied to another object.

However, if you return by value for operator=, you will call a constructor AND destructor EACH time that the assignment operator is called!!

So, given:

A& operator=(const A& rhs) { /* ... */ };

Then,

a = b = c; // calls assignment operator above twice. Nice and simple.

But,

A operator=(const A& rhs) { /* ... */ };

a = b = c; // calls assignment operator twice, calls copy constructor twice, calls destructor type to delete the temporary values! Very wasteful and nothing gained!

In sum, there is nothing gained by returning by value, but a lot to lose.

(Note: This isn’t meant to address the advantages of having the assignment operator return an lvalue. Read the other posts for why that might be preferable)

Leave a Comment