I know that the rule of thumb is that we return by reference iff the returned variable exists in the caller. Say we have a function:
int& f(int& a){ return a; }
Now, in the caller, I can call in 2 ways:
int a = 5;
int b1 = f(a); // 1
int& b2 = f(a); // 2
The difference is that change in b1 or a in the caller, doesn't effect one another, but changes in b2 or a in caller effects one another.
That means, what a was referring to int the callee is copied to b2, whereas, it seems like only the value a was referring to in the callee was copied to b1 because of the above statement.
Then what is the advantage of returning by referrence like 1st case if it copies as well. Example where statements like 1 are seen is copy assignment operator which returns by reference for chaining of assignments: eg: obj1 = obj2 = obj3;
Am I missing something here?
CodePudding user response:
Frankly your argument is moot.
Along the same line of reasoning you could argue that there is no advantage of using a reference in general, because it can be used to make a copy:
int x = 42;
int& ref = x;
int y = ref; // makes a copy
However, just because you can use a reference to make a copy does not decrease usability of a reference:
ref = 24; // does modify x
In your example:
int a = 5; int b1 = f(a); // 1 int& b2 = f(a); // 2
It has almost nothing to do with f
that the caller decided to make a copy in // 1
. Of course you can use a reference to make a copy. But you cannot use a copy to modify a
:
f(a) = 42; // modifies a
This only works as inteded (modify a
) when f
returns a reference.
As an analogy you could ask: Whats the advantage of using an airplane? Airplanes can drive on the ground just like cars can do ;)