Overloading assignment operator in C++

Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?

a = b; // huh, why does this create an unnecessary copy?

In addition, it would be surprising to users of your class, since the built-in assignment operator doesn't copy likewise

int &a = (some_int = 0); // works

A good general advice when overloading operators is 'do as primitive types do', and the default behavior of assignment to a primitive type is that.

Not returning anything could be an option, to disable assignment inside other expressions if you feel the need, but returning a copy does not make sense at all: if the caller wants to make a copy they can make it out of the reference, if they do not need the copy there is no need to generate a temporary that is not needed.


Cause f() can modify a. (we return a non-const reference)

If we return a value (a copy) of a, f() will modify the copy, not a