简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM