<jo***********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
What happens when you return a reference to a local variable?
Undefined behavior.
for example:
#include <iostream>
#include <cstdlib>
using namespace std;
int& testf()
{
int x = 1;
return x;
}
That's undefined behavior because x is an automatic object, whose life ends
at the time testf completes.
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.
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.
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?
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