Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Rvalue and Lvalue References | Section
C++ Pointers and References

bookRvalue and Lvalue References

Pyyhkäise näyttääksesi valikon

Lvalues and Rvalues

In C++, lvalues and rvalues are two basic categories of expressions:

  • Lvalue: an object or memory location that has a name and can appear on the left side of an assignment;
  • Rvalue: a temporary value or literal that does not have a persistent memory address and usually appears on the right side of an assignment.

Examples:

int x = 10;      // x is an lvalue, 10 is an rvalue
x = 20;         // x (lvalue) can be assigned a new value (rvalue 20)

Lvalue References

An lvalue reference allows you to create an alias for an existing variable (an lvalue). You declare it using a single &:

int a = 5;
int& ref = a;   // ref is an lvalue reference to a
ref = 8;        // changes the value of a to 8
  • Lvalue references cannot bind to rvalues (temporaries or literals).

Rvalue References

An rvalue reference allows you to bind a reference to a temporary value (an rvalue). You declare it using &&:

int&& temp = 42; // temp is an rvalue reference bound to the temporary value 42
  • Rvalue references cannot bind to lvalues (named variables).
  • They are useful for optimizing code, such as moving resources instead of copying them.

Reference Binding Rules

  • Lvalue references (&) bind to lvalues.
  • Rvalue references (&&) bind to rvalues.

Example:

int x = 7;
int& lref = x;      // valid: lref binds to lvalue x
// int& lref2 = 8;  // error: cannot bind lvalue reference to rvalue

int&& rref = 8;     // valid: rref binds to rvalue 8
// int&& rref2 = x; // error: cannot bind rvalue reference to lvalue

Understanding these concepts helps you write safer, more efficient C++ code, especially when working with modern features like move semantics.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 12

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 12
some-alt