question

abcabc-6368 avatar image
0 Votes"
abcabc-6368 asked abcabc-6368 commented

In C++ what is the difference between return by value and return by reference in the function?

Hi,

In C++ what is the difference between return by value and return by reference in the function?

When we need to use return by value and return by reference in the function?

Thanks.

c++
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

abcabc-6368 avatar image abcabc-6368 DavidLowndes-6766 ·

As per you suggested link, if we should not return reference of local variable in the function, then what is the use of returning reference , we can return the value itself. I could not understand , please help.

0 Votes 0 ·

Remember that a reference is essentially just a pointer.
You should never return a reference to a local variable because it won't exist once the function has existed.
Returning a reference to something should only be done with careful consideration... the lifetime of what you're referencing needs to exceed the lifetime/use of the returned reference.
Generally it's only of use if copying the returned item is expensive, and you're sure your normal use of it won't break the lifetime issue.

1 Vote 1 ·
Show more comments

0 Answers