Note:: l-value and r-value

學習 ModernC++ 中遇到 lvalue, rvalue 的坑

自己學習 Modern-CPP 的過程中,發現到處都是 lvalue & rvalue。自己嘗試整理了一下這兩個酷東西的差異、當作參數時的模樣。


Definition

l-value

  • ✅ Location / Address
  • ✅ Value
1
2
3
int a = 123;
    ^
    l-value
1
2
3
4
5
6
// GetValue() is l-value now.
// GetValue() return a lvalue reference.
int& GetValue() {
    static int value = 10; // Must be a persistent location.
    return value;
}

r-value

  • ❌ Location / Address
  • ✅ Value
1
2
3
int a = 123;
        ^^^
        r-value
1
2
3
4
5
// GetValue() is r-value
// It's return a temporary value 10
int GetValue() {
    return 10;
}

Some code snippet

Parameter that taking any value

  • Taking a value as parameter.
1
2
3
4
5
6
7
8
void SetValue(int value) {
}

int main() {
    int i = 10;
    SetValue(i);  // OK, passing a l-value.
    SetValue(10); // OK, passing a r-value.
}

l-value reference

  • Taking only a l-value reference as parameter.
1
2
3
4
5
6
7
8
void SetValue(int& value) { 
}

int main() {
    int i = 10;
    SetValue(i);  // OK, passing a l-value.
    SetValue(10); // ERROR!! Can't passing a r-value.
}

const l-value reference

  • Passing l-value and termporary value.
1
2
3
4
5
6
7
8
void SetValue(const int& value) { 
}

int main() {
    int i = 10;
    SetValue(i);  // OK, passing a l-value.
    SetValue(10); // OK, compiler will create a temp l-value.
}

r-value reference

  • Function only accept termporary value.
1
2
3
4
5
6
7
8
void SetValue(const int&& value) { 
}

int main() {
    int i = 10;
    SetValue(i);  // ERROR!! Can't bound l-value to r-value reference
    SetValue(10); // OK, passing a r-value
}
Built with Hugo
Theme Stack designed by Jimmy