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

前端 未结 9 2029
不思量自难忘°
不思量自难忘° 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:38

    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.

提交回复
热议问题