Search code examples
c++functionlvalue

"initial value of reference to non-const must be an lvalue" can be valid when returning from function?


Recently I was studying lvalue and rvalue concept.

When I do

int&z  = 0 ;

I get an expected error like :

initial value of reference to non-const must be an lvalue

However, when I do this with a function that returns lvalue reference like:

int& get_value(){
    static int x = 10;
    return x;
}

//This line turns out to be valid...
get_value() = 20;

I wonder why get_value() = 20; is valid.


Solution

  • The error message makes it quite clear:

    initial value of reference to non-const must be an lvalue

    (emphasis mine). So long as the reference is initially bound to an l-value, everything is fine (so long as you don't use a reference to a stack local variable, of course). The reference returned from get_value is bound to x which is an l-value, and that's allowed.

    Without the function, you are essentially writing:

    int x = 10;      // x is an l-value
    int &get_x = x;  // just a variable instead of a function
    get_x = 20;      // assignment is ok
    

    which is clearly ok.