编程语言
首页 > 编程语言> > C++ 中 lvalue (左值) 和 rvalue (右值) 的区分

C++ 中 lvalue (左值) 和 rvalue (右值) 的区分

作者:互联网

Reference from :

<The C++ Programming Language>

Chapter 6   Section 4.1   Page  166

 

 "Roughly, rvalue means  "a value that is not an lvalue", such as a temporary value (e.g., the value returned by a function)."

 

 

 

A more refined view of lvalue and rvalue :

  "There are two properties that matter for an object when it comes to addressing, copying, and moving: 

    • Has identity: The program has the name of, pointer to, or reference to the object so that it is
    possible to determine if two objects are the same, whether the value of the object has
    changed, etc.
    • Movable: The object may be moved from (i.e., we are allowed to move its value to another
    location and leave the object in a valid but unspecified state, rather than copying; §17.5 "

"It turns out that three of the four possible combinations of those two properties are needed to precisely
describe the C++ language rules (we have no need for objects that do not have identity and
cannot be moved). Using "m for movable" and "i for has identity," we can represent this classification
of expressions graphically: 

So, a classical lvalue is something that has identity and cannot be moved (because we could examine
it after a move), and a classical rvalue is anything that we are allowed to move from. The other
alternatives are prvalue ("pure rvalue"), glvalue ("generalized lvalue"), and xvalue ("x" for "extraordinary""
or "expert only"; the suggestions for the meaning of this "x" hav e been quite imaginative)."

 

For example :

void f(vector<string>& vs)
{
    vector<string>& v2 = std:move(vs); // move vs to v2
    //...
}

 

Here, std::move(vs) is an xvalue: it clearly has identity (we can refer to it as vs), but we have explicitly
given permission for it to be moved from by calling std::move() (§3.3.2, §35.5.1).
For practical programming, thinking in terms of rvalue and lvalue is usually sufficient. Note
that every expression is either an lvalue or an rvalue, but not both.

 

Summary : 


  lvalue :  An object that has identity but cannot move.

  rvalue:   An movable object which doesn't have an identity.

  xvalue: An object that has both identity and movability (x for expert).

 

标签:rvalue,右值,lvalue,move,object,value,identity
来源: https://www.cnblogs.com/cmoses/p/14391717.html