Search code examples
c++rvalue-referencetemporary-objects

Is a function-returned temporary object not always r-value?


struct Test
{
    Test()
    {}

    Test(const Test& other)
    {
        cout << "Copy" << endl;
    }

    Test(Test&& other)  
    {
        cout << "Move" << endl;
    }
};

Test* f()
{
    static Test t;
    return &t;
}

int main()
{   
    auto t = *f();
    return 0;
}

Output is: Copy

*f() is obviously an anonymous temporary object so that it should be an r-value and the move-constructor should be called. Why does the compiler treat *f() as an l-value?

Is it a bug of the compiler, or my understanding wrong?


Solution

  • The result of f() is an anonymous temporary object of type Test*. f() is an rvalue.

    *f() performs indirection through said pointer. As is always the case when using the indirection operator, the result is an lvalue.