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

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

    The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".

    In your example, foo is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:

    int& foo()
    {
        static int x;
        return x;
    }
    

    and would succeed by changing the value of x, when saying:

    foo() = 10;
    

提交回复
热议问题