Pages

Lvalue and Rvalue reference

Before C++0x, a variable could contain a value, a pointer to a value, or a reference to a value. C++0x makes a distintion between Lvalue reference - that represents a reference as was already known - and Rvalue reference. Here we see what are all these about, then we'll see what is the use of a Rvalue reference.

Let's declare three variables:

int i = 7; // 1.
int* pi = &i; // 2.
int& ri = i; // 3.

1. i is a variable of type int. Its value is an integer currently set to 7.
2. pi is a pointer to an int. It has been initialized with the address of i, so we say that it points to i.
3. ri is a reference to an int. It has been initialized as an alias of i.

Pointer and reference are not so different, both of them let us access to another memory location containing a value of a certain type. A difference is that we use a reference in a more natural way, the same of a "normal" value variable, while using a pointer requires dereferencing the pointer, leading to a more complicated syntax. On the other side a reference is less flexible, since it must be initialized with a referenced object that can't be changed anymore.

Now about the difference between Lvalue and Rvalue difference. As we have seen, a "classic" reference is associated at its creation to another variable that should be an Lvalue. Lvalue is short for "Left Value", meaning "something that could be on the left side of an assigment operator". What has to be on the right side is called, you should have guessed it, an Rvalue ("Right Value").

This means we can't write code like this:
int& j = 7; // this does not compile
As we said, a reference should be initialize with a Lvalue, but a literal like 7 can't be on the left side of an assignment.

If we want to create a reference associated with an Rvalue we can (now) use a Rvalue reference:
int&& j = 7;

All of this should be clear, the question is: way introducing Rvalue reference in C++? We'll see that in the next post.

No comments:

Post a Comment