In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A
, and the following:
A a1(param);
A a2 = a1;
A a3;
a3 = a2; //<--- this is the problematic line
The operator=
is defined as follows:
A A::operator=(const A& a)
{
if (this == &a)
{
return *this;
}
param = a.param;
return *this;
}
Best Answer
A bit of clarification as to why it's preferable to return by reference for
operator=
versus return by value --- as the chaina = 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:
Then,
But,
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)