What does “int& foo()” mean in C++?

前端 未结 9 1812
不思量自难忘°
不思量自难忘° 2021-01-30 11:59

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
9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 12:48

    The explanation is assuming that there is some reasonable implementation for foo which returns an lvalue reference to a valid int.

    Such an implementation might be:

    int a = 2; //global variable, lives until program termination
    
    int& foo() {
        return a;
    } 
    

    Now, since foo returns an lvalue reference, we can assign something to the return value, like so:

    foo() = 42;
    

    This will update the global a with the value 42, which we can check by accessing the variable directly or calling foo again:

    int main() {
        foo() = 42;
        std::cout << a;     //prints 42
        std::cout << foo(); //also prints 42
    }
    

提交回复
热议问题