Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why move assignment operator should return reference to *this [duplicate]

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)?

like image 483
vsoftco Avatar asked Dec 13 '25 16:12

vsoftco


1 Answers

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.

like image 139
Mike Seymour Avatar answered Dec 15 '25 09:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!