Assigning a rvalue to a lvalue reference

Viewed 138

I was watching a tutorial about rvalues and lvalues and I got a little confused.

int& GetValue()
{
    static int value = 5;
    return value;
}

int main()
{
    int a = GetValue();

    GetValue() = 8;

    std::cout << a << std::endl;
    std::cout << GetValue()  << std::endl;

    int b = GetValue();
    std::cout << b << std::endl;
    return 0;
}

This prints

5
8
8

I don't understand how GetValue() = 8; changes the value from 5 to 8. And now I always get 8 when you call GetValue().

4 Answers

a is a copy of the static variable in GetValue():

int a = GetValue();

Therefore, the later assignment:

GetValue() = 8;

doesn't affect the value of a. It does, however, modify the value of the static variable, value, which is retrieved twice afterward:

  • std::cout << GetValue() << std::endl;
  • int b = GetValue();

The value of value is first 5. Then you assign 8 to it.

This...

int& GetValue()
{
    static int value = 5;
    return value;
}

is roughly equivalent to this...

static int value = 5;
int& GetValue()
{
    return value;
}

Except that in the first case, value is scoped to the function, so you cannot access it "globaly"(actually in the second one you can only access it within the same translation unit).

With your piece of code, both would print out 5 8 8


This...

int& GetValue()
{
    static int value = 5;
    value = 2;
    return value;
}

is roughly equivalent to this...

static int value = 5;
int& GetValue()
{
    value = 2;
    return value;
}

and will return 2 every time.

static keywork used in GetValue() function with value variable. first when Getvalue is called on the top of main function, the variable value is created on the head, this means that the value is not a local variable(stock in the function stack frame), so you can get it's reference (int& return a reference to value), the variable will be alive even the GetValue finishes.

second, int a = GetValue(); the GetValue will return a reference to static variable value. the compiler will copy the contains of this reference to a variable. a is not a reference to static value, unless int& a is used.

third, GetValue()=8 return a reference to static variable value, then we asigned 8 to the return reference, so value is changed implicitly( one way to change a static variable )

finally, the static variable value is equal to 8, so GetValue() return 8 everytime you call it, unless you get a reference to static variable value, and change it.

this what explain, the serie of 8 in the ouput.

Related