Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
xmllmx Avatar asked Mar 18 '26 14:03

xmllmx


1 Answers

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.

like image 164
R. Martinho Fernandes Avatar answered Mar 20 '26 06:03

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!