Overloading assignment operator in C++

jasonline picture jasonline · Mar 15, 2010 · Viewed 8.2k times · Source

As I've understand, when overloading operator=, the return value should should be a non-const reference.


A& A::operator=( const A& )
{
    // check for self-assignment, do assignment

    return *this;
}

It is non-const to allow non-const member functions to be called in cases like:


( a = b ).f();

But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?

It's assumed that copy constructor is implemented correctly.

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Mar 15, 2010

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