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(); means that foo() returns a reference to a variable.
Consider this code:
#include
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
This code prints:
$ ./a.out k=5
Because foo() returns a reference to the global variable k.
In your revised code, you are casting the returned value to a reference, which is then invalid.