Parthib Biswas
Parthib Biswas

Reputation: 501

Is there any difference between reference and lvalue reference?

By reference, I mean the normal reference- the one which is used in "call by reference" functions. Is there a difference between this reference and lvalue reference?

Upvotes: 0

Views: 248

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476990

There are two kinds of references in C++: lvalue references and rvalue references. Both are references. A function argument that binds to either kind of reference is "passed by reference".

Lvalue references bind to lvalues, and const-lvalue references also bind to rvalues.*

Rvalue references only bind to rvalues and never to lvalues.

The utility of separating the two kinds of references lies in the fact that rvalue references can make the assumption that the referred-to value is not aliased (since it is either a pure rvalue (i.e. a temporary) or an xvalue deliberately declared to be eXpiring) and can thus be modified without anyone noticing.

This allows the concept of moving resources and transferring ownership, which could not be expressed properly in the type system before C++11, when rvalue references were introduced. Before then, there was only one kind of reference, the lvalue reference.


*) The Microsoft compiler also allows binding non-const lvalues references to rvalues. This is non-standard, suprising and confusing.


As a reminder, the taxonomy of value categories in C++ is this:

                value
               /     \
         glvalue      rvalue
         /     \      /    \
   lvalue       xvalue      prvalue

   T & f()      T && f()    T f()

Underneath is an example: The value category of the function call expression f() is as indicated provided that f has the respective declared return type (and T is not a reference type). Moreover, the return type of the function can be recovered as decltype(f()).

Upvotes: 4

Related Questions