William
William

Reputation: 1895

What's the difference between returning a reference and value when overloading operator=?

Look here:

class IntClass
{
public:
IntClass operator=(const IntClass& rhs);
IntClass();
~IntClass();
int value;

};

Implementation:

IntClass::IntClass()
{
}


IntClass::~IntClass()
{
}

IntClass IntClass::operator=(const IntClass& rhs)
{
    this->value = rhs.value;
    return *this;
}

As you can see I am not returning a reference to the class. From the examples of overloading the = operator I see that people return a reference. Why is this?

This still functions as intended:

IntClass a, b, c, d;

a.value = 20;

b = c = d = a;

printf("%d", b.value);
printf("%d", c.value);
printf("%d", d.value);

Output: 202020

p.s I know the public access to value is bad.

Upvotes: 1

Views: 104

Answers (1)

T.C.
T.C.

Reputation: 137310

First, having your assignment operator return by value means that you are making an extra copy. The copy can be expensive, and compilers usually cannot elide it. If we assume that copy assignment and copy construction have roughly the same cost, then returning by value basically doubles the cost of the assignment.

Second, if your assignment operator return a reference, the result of the assignment expression is an lvalue, which mimics the built-in assignment operator. If your assignment operator return by value, the result of the expression is an rvalue. This can have interesting consequences:

void f(IntClass &lv); 
void g(IntClass &&rv);
void g(const IntClass &clv);

IntClass x, y; 
y.value = 10;
f(x = y);  // compiles only if operator= returns IntClass & 
           // as non-const lvalue references cannot bind to a temporary
g(x = y);  // calls g(IntClass &&) if operator= returns IntClass
           // calls g(const IntClass &) if operator= returns IntClass &

Upvotes: 2

Related Questions