0

I've been brushing up on C++ in preparation for a class, and something that's stumped me is returning a reference vs. returning a value (also vs. returning a const reference, but that's not really part of the question). Something I've read in several places is that you'd want a function or method to return a reference so that it can be chained. For instance, the standard assignment operator allows you to do stuff like:

a = b = c = d;

Instead of having to do:

c = d;
b = c;
a = b;

What I'm having trouble wrapping my head around, or finding a simple explanation of, is why returning a reference allows you to do chaining while returning a value would not? What goes wrong with chaining when a value is returned?

dylosaur
  • 149
  • 2
  • 14
  • Why don't you **make** a [example]? (create a class, an assignment operator, try to make it return `void` versus `T&`, see if chained assignment works) It didn't that hard. – user202729 Feb 24 '21 at 05:01
  • Probably a duplicate of at least one of these [1](http://stackoverflow.com/q/5669813) [2](http://stackoverflow.com/q/9072169) [3](http://stackoverflow.com/q/3105798) [4](http://stackoverflow.com/q/21485366) [5](http://stackoverflow.com/q/15292892) [6](http://stackoverflow.com/q/5669813) [7](http://stackoverflow.com/q/4706690) [8](http://stackoverflow.com/q/7360775) [9](http://stackoverflow.com/q/9072169) – user202729 Feb 24 '21 at 05:03
  • @M.M I feel like I almost got it from your comment, could you elaborate a bit further? – dylosaur Feb 24 '21 at 05:32
  • 1
    actually my comment was bogus I now realize, so hopefully you didn't get it. Returning by value would work, just would be quite wasteful in terms of creating and destroying copies. – M.M Feb 24 '21 at 05:41
  • @M.M This is what I was getting confused about. As far as I could tell, returning void and just operating on the reference argument wouldn't allow chaining, but returning a value would allow chaining, it would just be wasteful because of all the copies and stuff. Does that understanding sound right? – dylosaur Feb 24 '21 at 05:53
  • Chaining works whether you return by-value or by-reference. Of course `a = b = c` means `a = (b = c)`, so `b = c` needs to return a value in order for this chaining to make sense. In the particular case of `operator=`, it's useless to return a copy of `b`, as a reference to it will always be valid. – hugo Feb 24 '21 at 08:24

0 Answers0