In this post, we are going to understand, What are lvalue & rValue in C++11 how to use . In C++ 11, we got the move semantics concepts. To understand move semantics lvalue and rValue concepts are important. So today we will understand what these concepts are:
What are lvalue & rValue in C++11 how to use
In C++ we have Variables and the values that these variables hold. Then further we have variables that hold values and the pointer variables that hold the address to which they point. We can understand the concept of lvalue and rvalue in simplest words:
- lvalue – an lvalue is that which points to a memory location on heap or stack.
- rValue – an rvalue is that that doesn’t point to any memory or anywhere. It’s just a value.
Let us understand more details with examples:
Progarm Example lvalue and rValue
How does it works
- var is variable and a variable is placed in memory like in this case it is on the stack. so var is an lvalue.
int var = 0;
- 0 is just a value and does not hold any memory on the stack or heap at least. of course, it will be part of the memory on CPU registers while processing.so here 0 is an rValue.an rvalue is a temporary object that has no name.
Now as you can see var is an lvalue and it has a memory location associated with it then it means it has an address associated with it. We can access that address by using & operator like this:
As it is an address then we can have a pointer variable to point to this address:
int num = &var;
On the other hand, 0 is an rvalue, it can be assigned to a variable, but the reverse is not true.
x = 0 ; // This is valid. 0 = x ; // This is not valid.
This is the simple concept of lvalue and rvalue. Understanding this becomes important when you want to learn about Move semantics in C++11 and above.