C ++ lvalue (left value) and rvalue (rvalue)

lvalue (left value) and rvalue (rvalue)

Yesterday met a write code like the following: "cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’",Code similar to the following

class MyClass {
    int data;
public:
    MyClass(int& e):data(e){};
};

int main(){
    MyClass c(10);
    return 0;
}

The compiler tells us: "can not be non-const lvalue and rvalue reference binding", inside there are two key words: lvalueand rvalue.

What is lvalue (left value)

A simple definition: the memory had to determine the memory address value of the expression object, which can be a variable name: int a;can be an assignment expression a=b, or string constants "cnblogs", in short, the easiest way is to compile the following identification of this sentence &(需要鉴别的表达式), can by compiling value is left.

Strictly defined: C ++ Document

What is the nature of value left?

  1. Can be taken address (&), above us is to use this method to identify the value left.

  2. It can be assigned, or copy assignment;

    //赋值
    int a = 10;
    //复制赋值
    int a(10);
  3. Left can initialize a reference value, which is our common references;

    int a=10;
    int& reference = a;

    Here are some common properties see more properties: C ++ Document

What is the rvalue (rvalue)

: Non-lvalue.

Common are literal (constant except string), post-increment-decrement expressiona++;a--;

What is the nature of the right value?

  1. The address can not be taken

    int a = 1;
    int* p = &(a++); //报错,a++是右值,不能被取地址,而++a是左值
  2. It can not be assigned or copy assignment

    42 = 10;//很明显会报错
  3. You can initialize const lvalue reference , which is why I begin with the program being given! , The document does not say you can initialize a non-const lvalue reference!

    class MyClass {
        int data;
    public:
        MyClass(int const& e):data(e){};  //这里的形参引用用const修饰就可以编译通过了!!!
    };
    
    int main(){
        MyClass c(10);
        return 0;
    }
  4. You can initialize rvalue reference; reference value because the right is beyond my scope of knowledge, and come back later learned supplement.

Guess you like

Origin www.cnblogs.com/rookiezjz/p/12350050.html