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

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

    int& foo();
    

    Declares a function named foo that returns a reference to an int. What that examples fails to do is give you a definition of that function that you could compile. If we use

    int & foo()
    {
        static int bar = 0;
        return bar;
    }
    

    Now we have a function that returns a reference to bar. since bar is static it will live on after the call to the function so returning a reference to it is safe. Now if we do

    foo() = 42;
    

    What happens is we assign 42 to bar since we assign to the reference and the reference is just an alias for bar. If we call the function again like

    std::cout << foo();
    

    It would print 42 since we set bar to that above.

提交回复
热议问题