    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Universal References in C++11</title>
        <link>https://members.accu.org/index.php/journals/1887</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #111 - October 2012 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c314/">o111</a>
                    (6)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c314-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c314+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Universal References in C++11</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 04 October 2012 15:40:20 +01:00 or Thu, 04 October 2012 15:40:20 +01:00</p>
<p><strong>Summary:</strong>&nbsp;C++11 provides a new reference syntax, T&amp;&amp;. Scott Meyers explains that it doesnâ€™t always mean â€˜rvalue referenceâ€™.</p>
<p><strong>Body:</strong>&nbsp;<p>Perhaps the most significant new feature in C++11 is rvalue references; theyâ€™re the foundation on which move semantics and perfect forwarding are built. (If youâ€™re unfamiliar with the basics of rvalue references, move semantics, or perfect forwarding, you may wish to read Thomas Beckerâ€™s overview before continuing. A full citation is provided in the â€˜Further informationâ€™ section at the end of this article.) </p>

<p>Syntactically, rvalue references are declared like â€˜normalâ€™ references (now known as <em>lvalue references</em>), except you use two ampersands instead of one. This function takes a parameter of type rvalue-reference-to-<code>Widget</code>:</p>

<pre class="programlisting">
  void f(Widget&amp;&amp; param);</pre>
  
<p>Given that rvalue references are declared using <code>&amp;&amp;</code>, it seems reasonable to assume that the presence of <code>&amp;&amp;</code> in a type declaration indicates an rvalue reference. That is not the case:</p>

<pre class="programlisting">
  Widget&amp;&amp; var1 = someWidget;
    // here, &quot;&amp;&amp;&quot; means rvalue reference

  auto&amp;&amp; var2 = var1;
    // here, &quot;&amp;&amp;&quot; does <em>not</em> mean rvalue reference

  template&lt;typename T&gt;
    void f(std::vector&lt;T&gt;&amp;&amp; param);
    // here, &quot;&amp;&amp;&quot; means rvalue reference
	
  template&lt;typename T&gt;
    void f(T&amp;&amp; param);
    // here, &quot;&amp;&amp;&quot;does <em>not</em> mean rvalue reference</pre>
	
<p>In this article, I describe the two meanings of <code>&amp;&amp;</code> in type declarations, explain how to tell them apart, and introduce new terminology that makes it possible to unambiguously communicate which meaning of <code>&amp;&amp;</code> is intended. Distinguishing the different meanings is important, because if you think â€˜rvalue referenceâ€™ whenever you see <code>&amp;&amp;</code> in a type declaration, youâ€™ll misread a lot of C++11 code.</p>

<p>The essence of the issue is that <code>&amp;&amp;</code> in a type declaration sometimes means rvalue reference, but sometimes it means <em>either</em> rvalue reference <em>or</em> lvalue reference. As such, some occurrences of <code>&amp;&amp;</code> in source code may actually have the meaning of <code>&amp;</code>, i.e., have the syntactic <em>appearance</em> of an rvalue reference (<code>&amp;&amp;</code>), but the <em>meaning</em> of an lvalue reference (<code>&amp;</code>). References where this is possible are more flexible than either lvalue references or rvalue references. Rvalue references may bind only to rvalues, for example, and lvalue references, in addition to being able to bind to lvalues, may bind to rvalues only under restricted circumstances.1 In contrast, references declared with <code>&amp;&amp;</code> that may be either lvalue references or rvalue references may bind to <em>anything</em>. Such unusually flexible references deserve their own name. I call them <em>universal references</em>.</p>

<p>The details of when <code>&amp;&amp;</code> indicates a universal reference (i.e., when <code>&amp;&amp;</code> in source code might actually mean <code>&amp;</code>) are tricky, so Iâ€™m going to postpone coverage of the minutiae until later. For now, letâ€™s focus on the following rule of thumb, because that is what you need to remember during day-to-day programming:</p>

<p class="lesson">If a variable or parameter is declared to have type <code>T&amp;&amp;</code> for some <strong>deduced type</strong> <code>T</code>, that variable or parameter is a <em>universal reference</em>.</p>

<p>The requirement that type deduction be involved limits the situations where universal references can be found. In practice, almost all universal references are parameters to function templates. Because the type deduction rules for <code>auto</code>-declared variables are essentially the same as for templates, itâ€™s also possible to have <code>auto</code>-declared universal references. These are uncommon in production code, but I show some in this article, because they are less verbose in examples than templates. In the â€˜Nitty gritty detailsâ€™ section of this article, I explain that itâ€™s also possible for universal references to arise in conjunction with uses of <code>typedef</code> and <code>decltype</code>, but until we get down to the nitty gritty details, Iâ€™m going to proceed as if universal references pertained only to function template parameters and auto-declared variables.</p>

<p>The constraint that the form of a universal reference be <code>T&amp;&amp;</code> is more significant than it may appear, but Iâ€™ll defer examination of that until a bit later. For now, please simply make a mental note of the requirement.</p>

<p>Like all references, universal references must be initialized, and it is a universal referenceâ€™s initializer that determines whether it represents an lvalue reference or an rvalue reference:</p>

<div class="lesson">
<ul>
	<li>If the expression initializing a universal reference is an lvalue, the universal reference becomes an lvalue reference.</li>
	
	<li>If the expression initializing the universal reference is an rvalue, the universal reference becomes an rvalue reference.</li>
</ul>
</div>

<p>This information is useful only if you are able to distinguish lvalues from rvalues. A precise definition for these terms is difficult to develop (the C++11 standard generally specifies whether an expression is an lvalue or an rvalue on a case-by-case basis), but in practice, the following suffices:</p>

<ul>
	<li>If you can take the address of an expression, the expression is an lvalue.</li>

	<li>If the type of an expression is an lvalue reference (e.g., <code>T&amp;</code> or <code>const T&amp;</code>, etc.), that expression is an lvalue.</li>

	<li>Otherwise, the expression is an rvalue. Conceptually (and typically also in fact), rvalues correspond to temporary objects, such as those returned from functions or created through implicit type conversions. Most literal values (e.g., <code>10</code> and <code>5.3</code>) are also rvalues.</li>
</ul>

<p>Consider again the following code from the beginning of this article:</p>

<pre class="programlisting">
  Widget&amp;&amp; var1 = someWidget
  auto&amp;&amp; var2 = var1;</pre>
  
<p>You can take the address of <code>var1</code>, so <code>var1</code> is an lvalue. <code>var2</code>â€™s type declaration of <code>auto&amp;&amp;</code> makes it a universal reference, and because itâ€™s being initialized with <code>var1</code> (an lvalue), <code>var2</code> becomes an lvalue reference. A casual reading of the source code could lead you to believe that <code>var2</code> was an rvalue reference; the <code>&amp;&amp;</code> in its declaration certainly suggests that conclusion. But because it is a universal reference being initialized with an lvalue, <code>var2</code> becomes an lvalue reference. Itâ€™s as if <code>var2</code> were declared like this:</p>
 
<pre class="programlisting">
  Widget&amp; var2 = var1;</pre>
  
<p>As noted above, if an expression has type lvalue reference, itâ€™s an lvalue. Consider this example:</p>

<pre class="programlisting">
  std::vector&lt;int&gt; v;
  ...
  auto&amp;&amp; val = v[0];
  // val becomes an lvalue reference (see below)</pre>
  
<p><code>val</code> is a universal reference, and itâ€™s being initialized with <code>v[0]</code>, i.e., with the result of a call to <code>std::vector&lt;int&gt;::operator[]</code>. That function returns an lvalue reference to an element of the vector.<a href="#FN01"><sup>1</sup></a> Because all lvalue references are lvalues, and because this lvalue is used to initialize <code>val</code>, <code>val</code> becomes an lvalue reference, even though itâ€™s declared with what looks like an rvalue reference.</p>

<p>I remarked that universal references are most common as parameters in template functions. Consider again this template from the beginning of this article:</p>

<pre class="programlisting">
  template&lt;typename T&gt;
    void f(T&amp;&amp; param);
    // &quot;&amp;&amp;&quot; <em>might</em> mean rvalue reference</pre>

<p>Given this call to <Code>
f</Code>
,</p>

<pre class="programlisting">
  f(10);  // 10 is an rvalue</pre>

<p><code>param</code> is initialized with the literal <code>10</code>, which, because you canâ€™t take its address, is an rvalue. That means that in the call to <code>f</code>, the universal reference <code>param</code> is initialized with an rvalue, so <code>param</code> becomes an rvalue reference â€“ in particular, <code>int&amp;&amp;</code>.</p>

<p>On the other hand, if <code>f</code> is called like this,</p>
 
<pre class="programlisting">
  int x = 10;
  f(x);  // x is an lvalue</pre>

<p><code>param</code> is initialized with the variable <code>x</code>, which, because you can take its address, is an lvalue. That means that in this call to <code>f</code>, the universal reference <code>param</code> is initialized with an lvalue, and <code>param</code> therefore becomes an lvalue reference â€“ <code>int&amp;</code>, to be precise.</p>

<p>The comment next to the declaration of <code>f</code> should now be clear: whether paramâ€™s type is an lvalue reference or an rvalue reference depends on what is passed when <code>f</code> is called. Sometimes <code>param</code> becomes an lvalue reference, and sometimes it becomes an rvalue reference. <code>param</code> really is a <em>universal reference</em>.</p>

<p>Remember that <code>&amp;&amp;</code> indicates a universal reference <em>only where type deduction takes place</em>. Where thereâ€™s no type deduction, thereâ€™s no universal reference. In such cases, <code>&amp;&amp;</code> in type declarations always means rvalue reference. Hence Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;typename T&gt;
void f(T&amp;&amp; param);
       // deduced parameter type â‡’ type deduction;
       // &amp;&amp; â‰¡ universal reference
template&lt;typename T&gt;
class Widget {
  ...
  Widget(Widget&amp;&amp; rhs);
       // fully specified parameter type â‡’ no type
       // deduction; &amp;&amp; â‰¡ rvalue reference
};
template&lt;typename T1&gt;
class Gadget {
  ...
  template &lt;typename T2&gt;
  Gadget(T2&amp;&amp; rhs);
        // deduced parameter type â‡’ type deduction;
  ...   // &amp;&amp; â‰¡ universal reference
};
void f(Widget&amp;&amp; param);
        // fully specified parameter type â‡’ no type
        // deduction; &amp;&amp; â‰¡ rvalue reference
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>Thereâ€™s nothing surprising about these examples. In each case, if you see <code>T&amp;&amp;</code> (where <code>T</code> is a template parameter), thereâ€™s type deduction, so youâ€™re looking at a universal reference. And if you see <code>&amp;&amp;</code> after a particular type name (e.g., <code>Widget&amp;&amp;</code>), youâ€™re looking at an rvalue reference.</p>

<p>I stated that the <em>form</em> of the reference declaration must be <code>T&amp;&amp;</code> in order for the reference to be universal. Thatâ€™s an important caveat. Look again at this declaration from the beginning of this article:</p>
 
<pre class="programlisting">
  template&lt;typename T&gt;
  void f(std::vector&lt;T&gt;&amp;&amp; param);
  // &quot;&amp;&amp;&quot; means rvalue reference</pre>
  
<p>Here, we have both type deduction and a <code>&amp;&amp;</code>-declared function parameter, but the form of the parameter declaration is not <code>T&amp;&amp;</code>, itâ€™s <code>std::vector&lt;T&gt;&amp;&amp;</code>. As a result, the parameter is a normal rvalue reference, not a universal reference. Universal references can only occur in the form <code>T&amp;&amp;</code>! Even the simple addition of a <code>const</code> qualifier is enough to disable the interpretation of <code>&amp;&amp;</code> as a universal reference:</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  void f(const T&amp;&amp; param);
  // &quot;&amp;&amp;&quot; means rvalue reference</pre>
  
<p>Now, <code>T&amp;&amp;</code> is simply the required <em>form</em> for a universal reference. It doesnâ€™t mean you have to use the name <code>T</code> for your template parameter: </p>
 
<pre class="programlisting">
  template&lt;typename MyTemplateParamType&gt;
  void f(MyTemplateParamType&amp;&amp; param);
  // &quot;&amp;&amp;&quot; means universal reference</pre>
  
<p>Sometimes you can see <code>T&amp;&amp;</code> in a function template declaration where <code>T</code> is a template parameter, yet thereâ€™s still no type deduction. Consider this <code>push_back</code> function in <code>std::vector</code>, shown in Listing 2.<a href="#FN02"><sup>2</sup></a></p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;class T,
          class Allocator = allocator&lt;T&gt; &gt;
class vector {
public:
  ...
  void push_back(T&amp;&amp; x);
  // fully specified parameter type â‡’ no type
  // deduction; &amp;&amp; â‰¡ rvalue reference
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>Here, <code>T</code> is a template parameter, and <code>push_back</code> takes a <code>T&amp;&amp;</code>, yet the parameter is not a universal reference! How can that be?</p>

<p>The answer becomes apparent if we look at how <code>push_back</code> would be declared outside the class. Iâ€™m going to pretend that <code>std::vector</code>â€™s <code>Allocator</code> parameter doesnâ€™t exist, because itâ€™s irrelevant to the discussion, and it just clutters up the code. With that in mind, hereâ€™s the declaration for this version of <code>std::vector::push_back</code>:</p>

<pre class="programlisting">
  template &lt;class T&gt;
  void vector&lt;T&gt;::push_back(T&amp;&amp; x);</pre>

<p><code>push_back</code> canâ€™t exist without the class <code>std::vector&lt;T&gt;</code> that contains it. But if we have a class <code>std::vector&lt;T&gt;</code>, we already know what <code>T</code> is, so thereâ€™s no need to deduce it.</p>

<p>An example will help. If I write</p>

<pre class="programlisting">
  Widget makeWidget();
  // factory function for Widget
  std::vector&lt;Widget&gt; vw;
  ...
  Widget w;
  vw.push_back(makeWidget());
  // create Widget from factory, add it to vw</pre>
  
<p>my use of <code>push_back</code> will cause the compiler to instantiate that function for the class <code>std::vector&lt;Widget&gt;</code>. The declaration for that <code>push_back</code> looks like this:</p>
 
<pre class="programlisting">
  void std::vector&lt;Widget&gt;::push_back(Widget&amp;&amp; x);</pre>
  
<p>See? Once we know that the class is <code>std::vector&lt;Widget&gt;</code>, the type of <code>push_back</code>â€™s parameter is fully determined: itâ€™s <code>Widget&amp;&amp;</code>. Thereâ€™s no role here for type deduction.</p>
<p>Contrast that with <code>std::vector</code>â€™s <code>emplace_back</code>, which is declared like Listing 3.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;class T,
          class Allocator = allocator&lt;T&gt; &gt;
class vector {
public:
  ...
  template &lt;class... Args&gt;
  void emplace_back(Args&amp;&amp;... args);
  // deduced parameter types â‡’ type deduction;
  ... // &amp;&amp; â‰¡ universal references
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>Donâ€™t let the fact that <code>emplace_back</code> takes a variable number of arguments (as indicated by the ellipses in the declarations for <code>Args</code> and <code>args</code>) distract you from the fact that a type for each of those arguments must be deduced. The function template parameter <code>Args</code> is independent of the class template parameter <code>T</code>, so even if we know that the class is, say, <code>std::vector&lt;Widget&gt;</code>, that doesnâ€™t tell us the type(s) taken by <code>emplace_back</code>. The out-of-class declaration for <code>emplace_back</code> for <code>std::vector&lt;Widget&gt;</code> makes that clear (Iâ€™m continuing to ignore the existence of the <code>Allocator</code> parameter):</p>
 
<pre class="programlisting">
  template&lt;class... Args&gt;
  void std::vector&lt;Widget&gt;::emplace_back
    (Args&amp;&amp;... args);</pre>
	
<p>Clearly, knowing that the class is <Code>
std::vector&lt;Widget&gt;</Code>
 doesnâ€™t eliminate the need for the compiler to deduce the type(s) passed to <Code>
emplace_back</Code>
. As a result, <Code>
std::vector::emplace_back</Code>
â€™s parameters are universal references, unlike the parameter to the version of <Code>
std::vector::push_back</Code>
 we examined, which is an rvalue reference.</p>

<p>A final point is worth bearing in mind: the lvalueness or rvalueness of an expression is independent of its type. Consider the type <code>int</code>. There are lvalues of type <code>int</code> (e.g., variables declared to be <code>int</code>s), and there are rvalues of type <code>int</code> (e.g., literals like <code>10</code>). Itâ€™s the same for user-defined types like <code>Widget</code>. A <code>Widget</code> object can be an lvalue (e.g., a <code>Widget</code> variable) or an rvalue (e.g., an object returned from a <code>Widget</code>-creating factory function). The type of an expression does not tell you whether it is an lvalue or an rvalue.</p>
<p>Because the lvalueness or rvalueness of an expression is independent of its type, itâ€™s possible to have <em>lvalues</em> whose type is <em>rvalue reference</em>, and itâ€™s also possible to have <em>rvalues</em> of the type <em>rvalue reference</em>:</p>

<pre class="programlisting">
  Widget makeWidget();
  // factory function for Widget
  
  Widget&amp;&amp; var1 = makeWidget()
  // var1 is an lvalue, but 
  // its type is rvalue reference (to Widget)
  
  Widget var2 = static_cast&lt;Widget&amp;&amp;&gt;(var1);
  // the cast expression yields an rvalue, but
  // its type is rvalue reference (to Widget)</pre>
  
<p>The conventional way to turn lvalues (such as <code>var1</code>) into rvalues is to use <code>std::move</code> on them, so <code>var2</code> could be defined like this:</p>

<pre class="programlisting">
  Widget var2 = std::move(var1);
  // equivalent to above</pre>
  
<p>I initially showed the code with <code>static_cast</code> only to make explicit that the type of the expression was an rvalue reference (<code>Widget&amp;&amp;</code>).</p>

<p>Named variables and parameters of rvalue reference type are lvalues. (You can take their addresses.) Consider again the <code>Widget</code> and <code>Gadget</code> templates from earlier, shown in Listing 4.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;typename T&gt;
class Widget {
  ...
  Widget(Widget&amp;&amp; rhs);
  // rhs's type is rvalue reference, but rhs
  // itself is an lvalue
  ...
};
template&lt;typename T1&gt;
class Gadget {
  ...
  template &lt;typename T2&gt;
  Gadget(T2&amp;&amp; rhs);
  // rhs is a universal reference whose type will
  // eventually become an rvalue reference or an
  // lvalue reference, but rhs itself is an lvalue
  ...
  };
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>
  
<p>In Widgetâ€™s constructor, <code>rhs</code> is an rvalue reference, so we know itâ€™s bound to an rvalue (i.e., an rvalue was passed to it), but <code>rhs</code> itself is an lvalue, so we have to convert it back to an rvalue if we want to take advantage of the rvalueness of what itâ€™s bound to. Our motivation for this is generally to use it as the source of a move operation, and thatâ€™s why the way to convert an lvalue to an rvalue is to use <code>std::move</code>. Similarly, <code>rhs</code> in <code>Gadget</code>â€™s constructor is a universal reference, so it might be bound to an lvalue or to an rvalue, but regardless of what itâ€™s bound to, <code>rhs</code> itself is an lvalue. If itâ€™s bound to an rvalue and we want to take advantage of the rvalueness of what itâ€™s bound to, we have to convert <code>rhs</code> back into an rvalue. If itâ€™s bound to an lvalue, of course, we donâ€™t want to treat it like an rvalue. This ambiguity regarding the lvalueness and rvalueness of what a universal reference is bound to is the motivation for <code>std::forward</code>: to take a universal reference lvalue and convert it into an rvalue only if the expression itâ€™s bound to is an rvalue. The name of the function (<code>forward</code>) is an acknowledgment that our desire to perform such a conversion is virtually always to preserve the calling argumentâ€™s lvalueness or rvalueness when passing â€“ <em>forwarding</em> â€“ it to another function.</p>

<p>But <code>std::move</code> and <code>std::forward</code> are not the focus of this article. The fact that <code>&amp;&amp;</code> in type declarations may or may not declare an rvalue reference is. To avoid diluting that focus, Iâ€™ll refer you to the references in the â€˜Further informationâ€™ section for information on <code>std::move</code> and <code>std::forward</code>.</p>

<h2>Nitty gritty details</h2>

<p>The true core of the issue is that some constructs in C++11 give rise to references to references, and references to references are not permitted in C++. If source code explicitly contains a reference to a reference, the code is invalid:</p>

<pre class="programlisting">
  Widget w1;
  ...
  Widget&amp; &amp; w2 = w1; // error!
  // No such thing as &quot;reference to reference&quot; </pre>

<p>There are cases, however, where references to references arise as a result of type manipulations that take place during compilation, and in such cases, rejecting the code would be problematic. We know this from experience with the initial standard for C++, i.e., C++98/C++03.</p>

<p>During type deduction for a template parameter that is a universal reference, lvalues and rvalues of the same type are deduced to have slightly different types. In particular, lvalues of type <code>T</code> are deduced to be of type <code>T&amp;</code> (i.e., lvalue reference to <code>T</code>), while rvalues of type <code>T</code> are deduced to be simply of type <code>T</code>. (Note that while lvalues are deduced to be lvalue references, rvalues are not deduced to be rvalue references!) Consider what happens when a template function taking a universal reference is invoked with an rvalue and with an lvalue:</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  void f(T&amp;&amp; param);
  ...
  int x;
  ...
  f(10);  // invoke f on rvalue
  f(x);   // invoke f on lvalue</pre>
  
<p>In the call to <code>f</code> with the rvalue <code>10</code>, <code>T</code> is deduced to be <code>int</code>, and the instantiated <code>f</code> looks like this:</p>
 
<pre class="programlisting">
void f(int&amp;&amp; param); // f instantiated from rvalue</pre>

<p>Thatâ€™s fine. In the call to <code>f</code> with the lvalue <code>x</code>, however, <code>T</code> is deduced to be <code>int&amp;</code>, and <code>f</code>â€™s instantiation contains a reference to a reference:</p>

<pre class="programlisting">
void f(int&amp; &amp;&amp; param);
  // initial instantiation of f with lvalue</pre>

<p>Because of the reference-to-reference, this instantiated code is <em>prima facie</em> invalid, but the source code â€“ <code>f(x)</code>â€“ is completely reasonable. To avoid rejecting it, C++11 performs â€˜reference collapsingâ€™ when references to references arise in contexts such as template instantiation. </p>

<p>Because there are two kinds of references (lvalue references and rvalue references), there are four possible reference-reference combinations: lvalue reference to lvalue reference, lvalue reference to rvalue reference, rvalue reference to lvalue reference, and rvalue refer-ence to rvalue reference. There are only two reference-collapsing rules:</p>

<ul>
	<li>An rvalue reference to an rvalue reference becomes (â€˜collapses intoâ€™) an rvalue reference.</li>
	<li>All other references to references (i.e., all combinations involving an lvalue reference) collapse into an lvalue reference.</li>
</ul>

<p>Applying these rules to the instantiation of <code>f</code> on an lvalue yields the following valid code, which is how the compiler treats the call:</p>
 
<pre class="programlisting">
void f(int&amp; param); // instantiation of f with
  // lvalue after reference collapsing</pre>

<p>This demonstrates the precise mechanism by which a universal reference can, after type deduction and reference collapsing, become an lvalue reference. The truth is that a universal reference is really just an rvalue reference in a reference-collapsing context.</p>

<p>Things get subtler when deducing the type for a variable that is itself a reference. In that case, the reference part of the type is ignored. For example, given</p>

<pre class="programlisting">
  int x;
  ...
  int&amp;&amp; r1 = 10; // r1's type is int&amp;&amp;
  int&amp; r2 = x;       // r2's type is int&amp;</pre>
  
<p>the type for both <code>r1</code> and <code>r2</code> is considered to be <code>int</code> in a call to the template <code>f</code>. This reference-stripping behavior is independent of the rule that, during type deduction for universal references, lvalues are deduced to be of type <code>T&amp;</code> and rvalues of type <code>T</code>, so given these calls,</p>

<pre class="programlisting">
  f(r1);
  f(r2);</pre>

<p>the deduced type for both <code>r1</code> and <code>r2</code> is <code>int&amp;</code>. Why? First the reference parts of <code>r1</code>â€™s and <code>r2</code>â€™s types are stripped off (yielding <code>int</code> in both cases), then, because each is an lvalue, each is treated as <code>int&amp;</code> during type deduction for the universal reference parameter in the call to <code>f</code>.</p>

<p>Reference collapsing occurs, as Iâ€™ve noted, in â€˜contexts such as template instantiationâ€™. A second such context is the definition of <code>auto</code> variables. Type deduction for <code>auto</code> variables that are universal references is essentially identical to type deduction for function template parameters that are universal references, so lvalues of type <code>T</code> are deduced to have type <code>T&amp;</code>, and rvalues of type <code>T</code> are deduced to have type <code>T</code>. Consider again this example from the beginning of this article:</p>

<pre class="programlisting">
  Widget&amp;&amp; var1 = someWidget;
  // var1 is of type Widget&amp;&amp; (no use of auto here)
  auto&amp;&amp; var2 = var1;
  // var2 is of type Widget&amp; (see below)</pre>

<p><code>var1</code> is of type <code>int&amp;&amp;</code>, but its reference-ness is ignored during type deduction in the initialization of <code>var2</code>; itâ€™s considered to be of type <code>Widget</code>. Because itâ€™s an lvalue being used to initialize a universal reference (<code>var2</code>), its deduced type is <code>Widget&amp;</code>. Substituting <code>Widget&amp;</code> for <code>auto</code> in the definition for <code>var2</code> yields the following invalid code:</p>

<pre class="programlisting">
  Widget&amp; &amp;&amp; var2 = var1;
  // note reference-to-reference</pre>

<p>which, after reference collapsing, becomes:</p>

<pre class="programlisting">
  Widget&amp; var2 = var1; // var2 is of type Widget&amp;</pre>

<p>A third reference-collapsing context is <code>typedef</code> formation and use. Given this class template,</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  class Widget {
  typedef T&amp; LvalueRefType;
  ...
  };</pre>
  
<p>and this use of the template,</p>

<pre class="programlisting">
  Widget&lt;int&amp;&gt; w;</pre>

<p>the instantiated class would contain this (invalid) <code>typedef</code>:</p>

<pre class="programlisting">
  typedef int&amp; &amp; LvalueRefType;</pre>
  
<p>Reference-collapsing reduces it to this legitimate code:</p>

<pre class="programlisting">
  typedef int&amp; LvalueRefType;</pre>

<p>If we then use this <code>typedef</code> in a context where references are applied to it, e.g.,</p>

<pre class="programlisting">
  void f(Widget&lt;int&amp;&gt;::LvalueRefType&amp;&amp; param);</pre>
  
<p>the following invalid code is produced after expansion of the <code>typedef</code>,</p>

<pre class="programlisting">
  void f(int&amp; &amp;&amp; param);</pre>
  
<p>but reference-collapsing kicks in, so <code>f</code>â€™s ultimate declaration is this:</p>

<pre class="programlisting">
  void f(int&amp; param);</pre>
  
<p>The final context in which reference-collapsing takes place is the use of <code>decltype</code>. As is the case with templates and <code>auto</code>, <code>decltype</code> performs type deduction on expressions that yield types that are either <code>T</code> or <code>T&amp;</code>, and <code>decltype</code> then applies C++11â€™s reference-collapsing rules. Alas, the type-deduction rules employed by <code>decltype</code> are not the same as those used during template or auto type deduction. The details are too arcane for coverage here (the â€˜Further informationâ€™ section provides pointers to, er, further information), but a noteworthy difference is that <code>decltype</code>, given a named variable of non-reference type, deduces the type <code>T</code> (i.e., a non-reference type), while under the same conditions, templates and <code>auto</code> deduce the type <code>T&amp;</code>. Another important difference is that <code>decltype</code>â€™s type deduction depends only on the <code>decltype</code> expression; the type of the initializing expression (if any) is ignored. Ergo Listing 5.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
Widget w1, w2;
auto&amp;&amp; v1 = w1;
// v1 is an auto-based universal reference being
// initialized with an lvalue, so v1 becomes an
// lvalue reference referring to w1.
decltype(w1)&amp;&amp; v2 = w2;
// v2 is a decltype-based universal reference, and
// decltype(w1) is Widget, so v2 becomes an rvalue
// reference.
// w2 is an lvalue, and it's not legal to
// initialize an rvalue reference with an lvalue,
// so this code does not compile.
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<h2>Summary</h2>

<p>In a type declaration, <code>&amp;&amp;</code> indicates either an rvalue reference or a <em>universal reference</em> â€“ a reference that may resolve to either an lvalue reference or an rvalue reference. Universal references always have the form <code>T&amp;&amp;</code> for some deduced type <code>T</code>.</p>

<p><em>Reference collapsing</em> is the mechanism that leads to universal references (which are really just rvalue references in situations where reference-collapsing takes place) sometimes resolving to lvalue references and sometimes to rvalue references. It occurs in specified contexts where references to references may arise during compilation. Those contexts are template type deduction, <code>auto</code> type deduction, <code>typedef</code> formation and use, and <code>decltype</code> expressions.</p>

<h2>Acknowledgments</h2>

<p>Draft versions of this article were reviewed by Cassio Neri, Michal Mocny, Howard Hinnant, Andrei Alexandrescu, Stephan T. Lavavej, Roger Orr, Chris Oldwood, Jonathan Wakely, and Anthony Williams. Their comments contributed to substantial improvements in the content of the article as well as in its presentation.</p>

<h2>Further information</h2>

<p class="bibliomixed">C++11, Wikipedia. <a href="http://en.wikipedia.org/wiki/C%2B%2B11">http://en.wikipedia.org/wiki/C%2B%2B11</a></p>

<p class="bibliomixed">Overview of the New C++ (C++11), Scott Meyers, Artima Press, last updated January 2012. <a href="http://www.artima.com/shop/overview_of_the_new_cpp">http://www.artima.com/shop/overview_of_the_new_cpp</a></p>

<p class="bibliomixed">C++ Rvalue References Explained, Thomas Becker, last updated September 2011. <a href="http://thbecker.net/articles/rvalue_references/section_01.html">http://thbecker.net/articles/rvalue_references/section_01.html</a></p>

<p class="bibliomixed">decltype, Wikipedia. <a href="http://en.wikipedia.org/wiki/Decltype">http://en.wikipedia.org/wiki/Decltype</a></p>

<p class="bibliomixed">â€˜A Note About decltypeâ€™, Andrew Koenig, <em>Dr. Dobbâ€™s</em>, 27 July 2011. http://drdobbs.com/blogs/cpp/231002789</p>

<p class="footnotes"></p>
<ol>
	<li><a id="FN01"></a>Iâ€™m ignoring the possibility of bounds violations. They yield undefined behavior.</li>
	<li><a id="FN02"></a><code>std::vector::push_back</code> is overloaded. The version shown is the only one that interests us in this article.</li>
</ol>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
