Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable's memory be accessed outside its scope?
return reference to local variable
Is it an undefined behavior when you return a ref. to a local variable ?
int & func(){
int x = 10;
return x;
}
int main() {
int &y = func();
cout << y << endl;
}
Yes it is. The variable is no longer available when the function ends.
You’re unlucky that it appears to work. The thing is, that memory isn’t cleared so the
10is still there, but it can be reclaimed at any time, so it’s definitely not safe.