const Rvalue References

Let’s learn about the const rvalue references.

We'll cover the following

What are rvalue references?

Let’s start with a quick recap on rvalue references. They were introduced in C++11. Since then, we have referred to the traditional references (marked with one &) as lvalue references.

Using rvalue (&&) references, we can avoid unnecessary copying by moving the values instead of making an extra copy. However, this method can potentially make the original values unusable.

MyObject a{param1, param2};
MyObject b = std::move(a);
a.foo() // Don't do this, it's unsafe, potentially a is in a default constructed state or worse

With the help of rvalue references, we can limit unnecessary copying and implement perfect forwarding functions, thus achieving higher performance and more robust libraries.

If we try to define rvalue references in contrast with lvalue references, we have to define lvalue references first. We can say that an lvalue is an expression whose address can be taken. Therefore, an lvalue reference is a locator value.

An rvalue is an unnamed value that exists only during the evaluation of an expression. In other words, we cannot take the address of an rvalue. An rvalue is not an lvalue.

Get hands-on with 1200+ tech skills courses.