Lvalues and Rvalues (C++)
In C++, every expression is either an lvalue or an rvalue, describing how the expression can be used, not what it is.
Lvalue
- Refers to an object with an identifiable memory location (you can take its address with
&). - Can appear on the left-hand side of an assignment.
int x = 5; // 'x' is an lvalue
x = 10; // Valid: 'x' can be assigned a new valueRvalue
- A temporary value that does not persist beyond the expression.
- Can appear only on the right-hand side of an assignment.
int y = 5; // '5' is an rvalue
x = y + 1; // Valid: 'y + 1' is an rvaluePurpose
Understanding these categories allows C++ to:
- Distinguish between copying and moving (via move semantics).
- Overload functions for lvalue and rvalue references
void f(const std::string& s); // takes lvalues
void f(std::string&& s); // takes rvalues (temporary objects)Note: && is an Rvalue Reference.