C++: lvalue, rvalue and rvalue references


C++ lvalue, rvalue, and rvalue references

Understanding lvalues, rvalues, and rvalue references is essential for mastering modern C++ features like move semantics and perfect forwarding.

πŸ“Œ What is an lvalue?

An lvalue refers to a location in memory β€” it has a name and can appear on the left-hand side of an assignment.

int x = 10;
x = 20;        // x is an lvalue
int* p = &x;   // can take address of x

πŸ“Œ What is an rvalue?

An rvalue is a temporary object or value that does not have a persistent memory address. It typically appears on the right-hand side of assignments.

int x = 10;
int y = x + 5;  // x + 5 is an rvalue
y = 100;        // 100 is an rvalue

You cannot take the address of an rvalue, and it usually lives only for the duration of the expression.

πŸ“Œ Rvalue references

C++11 introduced rvalue references using the `&&` syntax. This allows binding to rvalues and enables move semantics.

void process(int& x);   // lvalue reference
void process(int&& x);  // rvalue reference

int main() {
    int a = 42;
    process(a);        // calls int&
    process(10);       // calls int&&
}

Rvalue references are commonly used in move constructors, move assignment operators, and with `std::move`.

πŸ“Š lvalue vs rvalue Comparison

Feature lvalue rvalue
Has a name Yes Usually no
Can take address Yes No
Assignable (on left of =) Yes No
Lifetime Scope-based Temporary
Bindable to && No Yes

πŸ§ͺ std::move and move semantics

std::string a = "hello";
std::string b = std::move(a);  // a is "moved" into b

`std::move` doesn’t actually move anything β€” it simply casts an lvalue to an rvalue, enabling the move constructor or move assignment to take over.

πŸ’‘ When to use

  • Use lvalue references (&) when:
    • You want to read/write an existing named object
    • You don’t want to transfer ownership or modify resource ownership
  • Use rvalue references (&&) when:
    • You want to “steal” resources from a temporary
    • Implementing move constructors or move assignment
    • You want to optimize performance by avoiding deep copies

Summary

lvalues and rvalues are the building blocks of C++ expressions. Rvalue references unlock the power of move semantics and are vital for writing high-performance C++ code. Knowing how and when to use them is a core skill for modern C++ developers.

C/C++ Programming

–EOF (The Ultimate Computing & Technology Blog) —

554 words
Last Post: C++ assert vs static_assert
Next Post: ROS Topics, Services, and Actions Explained with Clear Examples

The Permanent URL is: C++: lvalue, rvalue and rvalue references (AMP Version)

Leave a Reply