modern c++, understanding of xvalue

477 Views Asked by At

Modern C++ only adds one new type "xvalue"? The right reference returned by a function is xvalue, this is defined, just like the right reference in the parameters of a function, which can only bind to right value? These understandings correct? The questions and answers related to this topic handle this q from learner's perspective of view. Here I try to get to know this topic from the designer's perspective of view. For example, int b =3; int&& x = std::move(b); this return value of std::move is a xvalue and it can bind to rreference, this is the rule set by the designer. (reasonable and usable). The designer also can set a rule that xvalue needs to bind left reference,even this is not a good rule.

1

There are 1 best solutions below

14
On

Be careful with terminology here. A function parameter or function return type might have/be an rvalue reference type, but is not an xvalue, because the term "xvalue" only applies to an expression.

Every expression is either an lvalue, an xvalue, or a prvalue. The most common sort of xvalue is an expression that calls a function that has an rvalue reference type as its return type. An expression that does a cast to an rvalue reference type is also an xvalue. There are a few other ways an expression can be an xvalue as well.

An rvalue reference is a type. A variable declared with an rvalue reference type can be initialized with either an xvalue or a prvalue, but not with an lvalue (unless via a user-defined conversion). Remember that the name of a variable declared as an rvalue reference is an lvalue, not an xvalue!

int n = 3;                          // 1
int&& r1 = static_cast<int&&>(n);   // 2
int&& r2 = std::move(r1);           // 3
int&& func(int&& arg);              // 4

The expressions in this code sample are:

  • 3 on line 1: a prvalue
  • n on line 2: an lvalue
  • static_cast<int&&>(n) on line 2: an xvalue
  • r1 on line 3: an lvalue
  • std::move(r1) on line 3: an xvalue

There are no expressions at all in line 4.