Reputation: 20919
Let's say we have a function
int increment(int x) {
return x+1;
}
Does it make any different to receive the return value by
const int foo = increment(8);
OR
const int& foo = increment(8);
?
What if a return type is a more complex and more sizable object? Does it make sense to use a reference to avoid an unnecessary copy?
I thought the returned value is out of the scope of the function (increment
in this example). So that one copy is needed anyway. Correct?
Upvotes: 0
Views: 70
Reputation: 238401
Does it make any different to receive the return value by ...
It doesn't make a difference in the sense that both have the same observable behaviour.
It does subjectively make difference in the sense that using the reference is more complex, and its understanding requires knowledge of more language rules. Lifetime extension of temporaries is a somewhat obscure language rule that is poorly understood by beginners as far as I know.
What if a return type is a more complex and more sizable object?
Doesn't matter.
Does it make sense to use a reference to avoid an unnecessary copy?
No copy is avoided. Instead of the local variable, the reference version creates a temporary object and the reference is bound to the temporary. It doesn't make sense to use a reference here.
Upvotes: 2