By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,478 Members | 1,684 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,478 IT Pros & Developers. It's quick & easy.

return type of a function that returns a local variable

P: n/a
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!

Mar 22 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 22 Mar, 12:11, "Jess" <w...@hotmail.comwrote:
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

Mar 22 '07 #2

P: n/a
Thanks, that solves my problem! :)

Mar 22 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.