I wondered why we should return a reference, when we overload operator = (assignment). On the one hand, most of the examples that I've seen (of overloading operator =), return a reference, but on the other hand, I saw few examples (of the same subject) that don't return a reference.
Can someone explain me, when we need to return a reference (specifically in operator = overloading), and give examples?
3 Answers 3
The main reason for returning a reference in operator= is because the old Assignable property for C++03 collection items, required it.
There is a corresponding requirement in C++11.
These requirements stemmed from the built-in operator=, which in turn got it from C, where it supported assignment chaining, e.g. writing
a = b = 666;
which is parsed as
a = (b = 666);
For a user-defined operator= it
is less efficient,
often more complex (e.g. for an iterator implementation) and
opens the door to Unholy Practices™ based on side-effects,
and so for a long time, until someone directed my attention to the standard library's requirements, I just defined operator= as returning void. More efficient, less verbose, no support for bad practices. But with such a requirement – it's yet another bad case of Frozen History™ – one simply must.
12 Comments
a = (b = 666); doesn't require an lvalue/reference to be returned by the assignment. As the previous answer mentioned, it's (a = b) = 666; that does.Returning a reference returns a modifiable value (lvalue). It allows the following:
(a = b) = c;
Ok, that one's a bit silly, but this one makes more sense:
++(a = b);
9 Comments
x = (y = 4);, the value returned by the inner assignment doesn't need to be modifiable since nothing writes to it, and the value returned by the outer assignment doesn't need to be modifiable since it's discarded.$new = $old =~ s/.../.../r; to perform a substitution on variable $old and store the result in $new. But before 5.14, substitutions were always done in-place, so you'd have to use the following to get the same effect: $new = $old; $new =~ s/.../.../; But since the assignment operator returns an lvalue (reference), you could write that as ($new = $old) =~ s/.../.../;One reason is because of efficiency. By passing and returning references in overloading the assignment operator, you prevent a lot of constructors and copy constructors from being called.
2 Comments
Explore related questions
See similar questions with these tags.