Saturday, July 18, 2026

lvalue vs rvalue

 

1. What is an lvalue?

An lvalue is an object that:

  • Has an identifiable memory location.
  • Has a name (in most cases).
  • Can appear on the left-hand side of an assignment.

Example:

int x = 10;

Here:

  • x is an lvalue.

2. What is an rvalue?

An rvalue is a temporary value that:

  • Usually does not have a persistent identity.
  • Is typically not assigned to directly.
  • Is often created as the result of an expression.

Examples:

20
x + y
std::string("Hello")

These are rvalues.


3. Why doesn't this compile?

int x = 10;
int&& r = x;   // Error

Because:

  • x is an lvalue.
  • An rvalue reference (&&) can only bind to an rvalue.

If you want to bind x to an rvalue reference, you must explicitly say you're willing to treat it as an rvalue:

int&& r = std::move(x);

std::move(x) converts x into an rvalue.


4. Why are rvalue references useful?

They enable move semantics.

Instead of copying expensive resources (like dynamically allocated memory), C++ can transfer ownership of those resources, improving performance.


Interview Tip

A senior interviewer may ask:

Is std::move() actually moving the object?

The best answer is:

No. std::move() simply casts an lvalue to an rvalue reference. The actual move happens when a move constructor or move assignment operator is invoked.

No comments:

Post a Comment

lvalue vs rvalue

  1. What is an lvalue? An lvalue is an object that: Has an identifiable memory location. Has a name (in most cases). Can appear on th...