I have a theoretical question:
Usually, in an operator= implementation, it returns *this. But what happens if we instead returned *other, where other is the right hand side of the assignment?
Thanks
I have a theoretical question:
Usually, in an operator= implementation, it returns *this. But what happens if we instead returned *other, where other is the right hand side of the assignment?
Thanks
The purpose of returning *this
from the assignment operator is to allow for assignment chaining, e.g.
int x = 2;
int y = x = 5; // Equivalent to: 'int y = (x = 5);'
The copy assignment operator is usually declared as:
T& operator=(const T& other);
Here the argument other
is declared as const
and can thus not be returned. Returning by const T&
will also act differently as the caller can not assign to the returned reference, thus disallowing assignment chaining.
Often you will also assign with a temporary. If you customize the behaviour of the assignment operator to return a reference to this temporary it can result in dangling references and other dangerous behaviours.
std::string s;
(s = "abc") = "def"; // Can't assign to rhs.
It is possible to customize the behaviour of the assignment operator to achieve different behaviours, but you should generally refrain from doing so to keep the meaning of the operator clear. If you want custom behaviour it's better to provide a function with a good descriptive name.
More info about operator overloading can be found here.
Reason for returning *this is to enable assignment in this form
a = b = c
this is same as
a.operator=( b.operator=(c))
If you return other, compiler wont be able to compile this kind of assignments.
Well their will be two factual differences :
const
instance from your operator=
or a copyMostly what this means is you will surprise some developers that might exploit the return value of your assignment thinking it gives back the left hand side as most objects do.
But there is not so many people who sanely intend to write things like:
(a = b).do_action();
And since you just assigned the right value to the left one and you are returning either a const
instance or a copy, most of the operations will most likely result in the same thing no matter if they are called on the left or right instance. So basically most of the time it won't change anything to your life.
However except if you are a boost::spirit
developer, you are highly encouraged to avoid such things for the sanity of your colleagues :)