Ali Çehreli wrote:[color=blue]
> <jois.de.vivre@gmail.com> wrote in message
> news:1126646349.707425.237510@f14g2000cwb.googlegr oups.com...[color=green]
> > What happens when you return a reference to a local variable?[/color]
>
> Undefined behavior.
>[color=green]
> > for example:
> >
> > #include <iostream>
> > #include <cstdlib>
> > using namespace std;
> >
> > int& testf()
> > {
> > int x = 1;
> > return x;
> > }[/color]
>
> That's undefined behavior because x is an automatic object, whose life ends
> at the time testf completes.
>[color=green]
> > int main(int argc, char *argv[])
> > {
> > int &y = testf();
> > cout << y << endl;
> > return 0;
> > }
> > //--------end sample code
> >
> > This results in outputting "1", but I don't understand whether that
> > makes sense intuitively.[/color]
>
> Undefined behavior sometimes results in meaningful things to happen. You see
> 1 likely because nobody writes anything else on the memory where x lived a
> little while ago. That memory still contains 1, and the invalid access to
> that memory treats it as int and displays 1.
>[color=green]
> > Wouldn't the local variable 'x' in testf() be
> > deallocated after the function returns? What, then would 'y' be
> > referencing? How come the compiler even allows this?[/color]
>
> Your compiler may be asked to warn you in such cases. g++, even without
> using any warning options says:
>
> warning: reference to local variable `x' returned
>
> Ali
> --
> Plug: ACCU's Silicon Valley Chapter meets on second Tuesdays. The meetings
> are open to public and free of charge. Please come tonight for a talk on
> Ada:
>
>
http://accu-usa.org/index.html[/color]
Great, Thanks!