return type of a function that returns a local variable

J

Jess

Hello,

I understand that if a function "f" has a local variable "a", and
after it returns, "a" vanishes. If "f" returns "a" as a result, then I
noticed the following:

1. if the return type is "a&", then compiler complains reference to
the local variable "a".
2. if the return type is "a", then everything works fine.

I think this is because in the first case, the return is copy-by-
reference, and we can't reference a local var. In the second case, it
is a copy-by-value, and it's correct because we can copy the value
from a local var, is this right?

Thanks!
 
G

Gavin Deane

Hello,

I understand that if a function "f" has a local variable "a", and
after it returns, "a" vanishes. If "f" returns "a" as a result, then I
noticed the following:

1. if the return type is "a&", then compiler complains reference to
the local variable "a".
2. if the return type is "a", then everything works fine.

Your description is a bit confused. In your first paragraph a is an
object, in your second a is a type. But I think I understand what you
mean.
I think this is because in the first case, the return is copy-by-
reference, and we can't reference a local var. In the second case, it
is a copy-by-value, and it's correct because we can copy the value
from a local var, is this right?

Yes.

// foo1 is bad. Don't do this.
int& foo1()
{
int i = 42;
return i;
}

// foo2 is OK.
int foo2()
{
int j = 0;
return j;
}

int main()
{
int& int_reference = foo1();
int int_value = foo2();
}

In the code above, in the function main, int_reference is initialised
as a *reference to* the int i inside function foo1. As you correctly
suspect, after foo1 returns i no longer exists and so int_reference
refers to nothing. It is a dangling reference. Any use of
int_reference has undefined behaviour.

int_value on the other hand is initialised with *a copy* of the int j
from inside function foo2. It doesn't matter that j no longer exists
after foo2 returns because the copy of j was taken while j did still
exist.

Gavin Deane
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top