While reading this explanation on lvalues and rvalues, these lines of code stuck out to me:
int& foo();
foo() = 42; // OK, foo() is an lvalue
int& foo();
Declares a function named foo that returns a reference to an int
. What that examples fails to do is give you a definition of that function that you could compile. If we use
int & foo()
{
static int bar = 0;
return bar;
}
Now we have a function that returns a reference to bar
. since bar is static
it will live on after the call to the function so returning a reference to it is safe. Now if we do
foo() = 42;
What happens is we assign 42 to bar
since we assign to the reference and the reference is just an alias for bar
. If we call the function again like
std::cout << foo();
It would print 42 since we set bar
to that above.