Reputation: 130
I'm learning about lvalue/rvalue and there is an example about lvalue:
int& foo();
foo() = 42; // ok, foo() is an lvalue
Normally people will let foo() return a global variable or a static varible inside its body, but if we define a local variable inside foo's body, it also works (with warning: reference to stack memory associated with local variable 'i' returned [-Wreturn-stack-address]):
#include <iostream>
using namespace std;
int &foo(){int i=7; return i;};
int main() {
foo() = 42;
return 0;
}
Why this is allowed in C++, is it a closure?
Upvotes: 0
Views: 34
Reputation: 52471
This program exhibits undefined behavior, by way of accessing an object after its lifetime has ended.
It's pointless to return a reference to a local variable - any use of such a reference by the caller is undefined, since the local variable is necessarily destroyed by that time.
Upvotes: 2