lvalue, rvalue
-
lvalue(locator value): Anything that can hold a address. Appear
on the left-hand side of an assignment.
rvalue(read value): temporary value that does not occupy a persistent memory location. Appears on the right-hand side of an assignment
int a = 10; // a is l value
// 10 is rvalue
int x = a+b; // x is l value
// a+b is rvalue
lvalue reference or Reference Variable (&)
-
Reference to bind to lvalue. This is same as reference variable
Usage: Pass large objects without copying.
int a = 10;
int &b = a; // lvalue reference
b = 11;
cout << a; // 11
-
Example:
Copy Constructor
is lvalue reference
rvalue reference (&&)
Reference that binds to an rvalue(temporary value)
int a = 10; //10 is rvalue
int &&b = 10; // b is rvalue reference
Usage of rvalue reference:
rvalues do occupy space in RAM ie they are temporaries on the
stack or directly inside a CPU register.
When we write int &&b = 10;, two things happen:
The temporary value 10 is placed into stack.
The rvalue reference
b extends the lifetime of that temporary so it
stays alive as long as b is in scope.
-> The biggest use case of rvalue references is moving data
instead of copying it (Move Semantics).
-> Imagine you have a class that manages a large block of heap
memory (like std::string or std::vector). Traditional copy would
allocate new memory and copy every single element over.
-> An rvalue reference tells the compiler: "This temporary
object is about to die anyway, so don't copy its data—just steal its
internal pointer."
XValue / Expiring Value
- (b+c) is called xvalue/temporary value which is ready to expire
a = b+c;
PRValue / Pure R Value
- Literal value is called pure R value
a = 42;