简体   繁体   English

为什么函数调用是xvalue(如果返回类型是rvalue)?

[英]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. 都是xvalue。 But why? 但为什么? Why aren't they prvalue? 他们为什么不prvalue? I'm a little bit confused. 我有点困惑。

Because you are returning by reference, not by value, from f . 因为您要从f返回引用,而不是返回值。 This implies that the A has a lifetime longer than f() , eg 这意味着A的寿命比f() ,例如

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; f().m; , the use of m inherits the value category of the earlier sub-expression, as normal for member access. ,对于成员访问来说, m的使用通常会继承早期子表达式的值类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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