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

Зміст курсу

C++ Pointers and References

C++ Pointers and References

1. Pointers Fundamentals
2. Pointer Arithmetic
3. References Fundamentals
4. Dynamic Memory Allocation

bookRvalue and Lvalue References

Concepts lvalue and rvalue are related to the classification of expressions.

  • lvalue (left value): is an expression that refers to an object with identifiable memory location. It represents an object that can be modified;

  • rvalue (right value): is an expression that represents a temporary or disposable value.

Temporary Values

A temporary value is a short-lived, intermediate result created during the evaluation of an expression. For example:

Temporary values are automatically managed by the compiler, and they exist for the duration of the expression or operation where they are created. After that, they are typically discarded, and the result is stored in the target variable or used as needed.

Move semantics

An rvalue reference is denoted by the double ampersand (&&).

The only difference between an lvalue and rvalue reference is that rvalue can be bound to a temporary object, whereas an lvalue reference cannot.

Note

Using an rvalue reference in this context might not be very practical, as there is no benefit to using an rvalue reference for a simple literal

A combination of lvalue and rvalue references is used to support move semantics, allowing resources to be transferred from one object to another without unnecessary copying. Look at the example below:

But we don't need copies of a or b. We simply wanted to swap them. Let's try again.

cpp

main

copy
1234567891011121314151617181920212223
#include <iostream> void swap(std::string &a, std::string &b) { // Move the content of a into temp std::string temp(std::move(a)); // Move the content of b into a a = std::move(b); // Move the content of temp into b b = std::move(temp); } int main() { std::string a = "Hello\n"; std::string b = "Bye\n"; swap(a, b); std::cout << a << b; }

std::move(): transforms an lvalue into an rvalue reference, enabling move semantics and the transfer or ownership without copying.

Note

We will go into detail about move semantics in the C++ OOP course since it's widely used in that context

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt