In this article we will discuss what is rvalue reference and how it is different from lvalue reference.

lvalue references

Prior to C++11 we only had references i.e. A Reference variable is an alias that always points to a an existing variable i.e.

With C++11 this reference has become lvalue reference and it can refer to lvalues only i.e.

Here, lvalueRef is a lvalue reference pointing to a lvalue x. A lvalue reference can not point to a rvalue i.e.

Here lvalueRef2 is a lvalue reference, so it cannot point to a rvalue.

rvalue Reference

rvalue references are introduced in C++11 and rvalue references can do what lvalue references fails to do i.e. a rvalue reference can refer to rvalues.

Declaring rvalue reference

To declare a rvalue reference, we need to specify two & operator i.e. &&.

Here, rvalueRef is rvalue reference which is pointing to a rvalue i.e. (x+1).

Let’s see an another example,

getData() is a rvalue. So, only rvalue reference can refer to it. If lvalue reference will try to refer to it then will result in compile error i.e.

Although const lvalue reference can refer to temporary object returned by getData() but as its a const reference, so we can not modify this temporary.

But a rvalue reference can refer to rvalue without const i.e.

Now, as we understand the rvalue references, the next question that comes in mind is, What was the need of rvalue references in C++11 ?


Well, we will discuss it in next articles.



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.