Can someone explain why the move assignment operator is (usually) declared as
Foo& operator=(Foo&&);
Why return a reference and not e.g. Foo or Foo&&? I understand why we want this for the regular assignment operator, due to associativeness rules as (a=b)=c being logically broken (although still compilable) if not returned by reference, but why is this the case when the RHS is a rvalue (xvalue/prvalue)?
Returning Foo is potentially expensive, and impossible if the type isn't copyable. It's also surprising: (a=b)=c would create a temporary and assign c to that, when you'd expect both assignments to be to a.
Returning Foo&& is just weird; you don't want things mysteriously turning into rvalues so that e.g. f(a=b) unexpectedly moves from a without you telling it to.
Returning Foo& is the conventional way to make the operator behave in an unsurprising way if you chain it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With