Why a function call is an xvalue (if return type is an rvalue)?

69 Views Asked by At

Let's say we have a function:

struct A {
    int m;
};

A&& f();

As far as I know the expressions:

f();
f().m; 

are both xvalue. But why? Why aren't they prvalue? I'm a little bit confused.

1

There are 1 best solutions below

2
Caleth On

Because you are returning by reference, not by value, from f. This implies that the A has a lifetime longer than f(), e.g.

A&& f()
{
     static A res;
     return std::move(res);
}

or

A global;

A&& f()
{
     return std::move(global);
}

But not

A&& f()
{
     return {}; // dangling reference
}

In f().m;, the use of m inherits the value category of the earlier sub-expression, as normal for member access.