Reference of Reference in C++

C++

C++ Problem Overview


I see code on StackOverflow every once in a while, asking about some overload ambiguity with something involving a function like:

void foo(int&& param);

My question is: Why does this even come up? Or rather, when would you ever have "a reference to a reference"? How is that any different from a plain old reference? I've never run across this in real-world code, so I'm curious as to what kind of code would need this.

C++ Solutions


Solution 1 - C++

It's a rvalue reference, Bjarne describes it here.

Shameless copying ("quoting"):

> The rvalue reference > > An rvalue reference is a compound type > very similar to C++'s traditional > reference. To better distinguish these > two types, we refer to a traditional > C++ reference as an lvalue reference. > When the term reference is used, it > refers to both kinds of reference: > lvalue reference and rvalue reference. > > An lvalue reference is formed by > placing an & after some type. > A a; A& a_ref1 = a; // an lvalue reference > > > An rvalue reference is formed by > placing an && after some type. > A a; A&& a_ref2 = a; // an rvalue reference > > An rvalue reference behaves just like > an lvalue reference except that it can > bind to a temporary (an rvalue), > whereas you can not bind a (non const) > lvalue reference to an rvalue. > A& a_ref3 = A(); // Error! A&& a_ref4 = A(); // Ok

Solution 2 - C++

It isn't a reference to a reference: such a thing does not exist.

It is an rvalue reference, a new feature added in C++11.

Solution 3 - C++

It's an rvalue reference. Note that the && token used for Boolean AND and rvalue references, and the & token used for bitwise AND and normal references, are different "words" as far as the language can tell.

An rvalue reference is (usually) bound to an object which may be left in an indeterminate state after the rvalue reference is finished, presumably because the object will then be destroyed.

Simply put, binding a variable to an rvalue reference is the usually the last thing you do to it.

Unlike a regular reference but like a const & reference, an rvalue reference can bind to an rvalue (an expression whose address cannot be directly taken). Like a regular reference but unlike a const & reference, an rvalue reference can be used to modify its object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser541686View Question on Stackoverflow
Solution 1 - C++SkurmedelView Answer on Stackoverflow
Solution 2 - C++James McNellisView Answer on Stackoverflow
Solution 3 - C++PotatoswatterView Answer on Stackoverflow