I am reading some C++ text at the address: https://cs.senecac.on.ca/~chris.szalwinski/archives/oop244.071/content/custo_p.html.
In the section RETURNING A REFERENCE, the author wrote:
”
Returning a reference from a function has two intrinsic benefits:
-
efficiency
-
creates an lvalue
“
I can understand the first benefit (efficiency), but do not understand why is the second one.
As the author explained, I can understand that what is lvalue, but I do not understand what is the relationship between the lvalue and returning a reference from a function so that lvalue becomes a benefit?
That simply means that you can assign something to the result of the function. Consider this example:
Instead of
int, this works with class objects as well, of course. The point is that by returning a reference toxthe caller can directly assign the locally scoped variable infoo. This is what the author means by saying that a reference return value "creates an lvalue".By the way, the example actually has an application, as it solves the static initialisation order fiasco for more complex types than
int.Edit
As for the "benefit", there are several ways to interpret this. Either it is a way of making your code more readable (as opposed to the same functionality implemented with pointers) or that you can use operations that can only be applied to an lvalue, which would not be possible if you would not return a reference/pointer but received an argument: