    <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  :: Two Daemons</title>
        <link>https://members.accu.org/index.php/articles/2135</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>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #128 - August 2015</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/articles/">All</a>

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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c352/">o128</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-352/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+352/">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;Two Daemons</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 04 August 2015 13:13:36 +01:00 or Tue, 04 August 2015 13:13:36 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Most people have come across C++11â€™s forwarding references. Dietmar KÃ¼hl explains what &amp;&amp; really means.</p>
<p><strong>Body:</strong>&nbsp;<p>When playing Nethack [<a href="#[Nethack]">Nethack</a>] using the traditional terminal-based interface you may be confronted by a monster taking the form of a <code>&amp;</code> character: a daemon of some sort. Depending on your level of experience, facing one daemon is often OK but facing two tends to get you into way more trouble. Since the release of C++11 we are frequently faced with the two daemons <code>&amp;&amp;</code>!</p>

<p>Now, if you think that the two characters next to each other represent the two daemons, youâ€™d be right in the Nethack sense. In C++ any instance of these two characters applied to a type actually represents one of two daemons. When you have got a <code>T&amp;&amp;</code> it is either a reference to an object which can be moved from or it is an entity whose type is deduced to match what the entity is initialized with. It uses exactly the same notation for two entirely different things! To relieve you from being haunted by these daemons and rather be prepared to fight them, Iâ€™ll describe below how these entities differ. In addition, Iâ€™ll show how you may use these insights to support movable entities with pre-C++11 compilers to some extent.</p>

<h2>How to know when to move</h2>

<p>First letâ€™s make a quick detour. In C++ a lot of temporary objects are floating around. When functions or expressions return their results as values you get a â€˜temporaryâ€™. If the temporary isnâ€™t of a simple data type, it may be quite involved and expensive to copy. On the other hand, since they are temporaries, there isnâ€™t much use in them as they are about to be destroyed! Instead of copying a temporary to get the value elsewhere and destroying the temporary, it makes much more sense to move the temporaryâ€™s content if it is expensive.</p>

<p>It would be great if we could indicate whether an object shall be moved or copied! The C++ approach to indicate different processing is to use different types. Since lvalue references are already used to indicate copying and we donâ€™t want to move lvalues by accident, we could reasonably use a different type, letâ€™s call it <code>movable_ref&lt;X&gt;</code>, to indicate that an object can be moved (bear with me â€“ I know about <code>X&amp;&amp;</code> and Iâ€™ll get to this).</p>

<p>If a type is used to indicate that an object can be moved, the compiler can choose an appropriate overload of a function which may move from the object. For example, a class supporting a move construction could be declared like Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class foo {
  // ...
public:
  foo(foo const&amp; other);
      // well-known copy
  foo(movable_ref&lt;foo&gt; other);
      // move the referenced object
  // ...
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>It is even possible to implement <code>movable_ref&lt;X&gt;</code> using a pre-C++11 compiler! All it takes is a class which internally holds a reference to an object indicating that the object wonâ€™t be used again and to provide suitable access to that reference. For example, a corresponding class template and a suitable factory function could look something like Listing 2 (see the â€˜Further readingâ€™ for a pointer to a complete implementation).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;typename T&gt;
class movable_ref {
  // suitable friend declaration goes here
  T* pointer;
  explicit movable_ref(T&amp; object):
    pointer(&amp;object) {}
public:
  operator T&amp;() const { return *this-&gt;pointer; }
};
template &lt;typename T&gt;
movable_ref&lt;T&gt; move(T&amp; object) {
  return movable_ref&lt;T&gt;(object);
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>With roughly the declaration in Listing 2, it is possible to use a simple expression like <code>move(x)</code> to create an object which indicates that the content of <code>x</code> can be transferred! This works like a charm for lvalues. For temporaries things become a little bit harder: a temporary cannot be bound to a non-<code>const</code> reference but it would still be desirable to move them. Carrying on just a little bit more with the class template above, it would be possible to create a <code>move()</code> member function for types which need to be moved. For example, the <code>move()</code> operation of a <code>std::string</code> could look like this:</p>

<pre class="programlisting">
  movable_ref&lt;std::string&gt; std::string::move() {
    return ::move(*this); }</pre>

<p>Note that temporaries are non-<code>const</code>. They just canâ€™t be bound to non-const lvalue reference. It is entirely possible to call a non-<code>const</code> member function like <code>std::string::move()</code> on them (assuming such a function exists)! So creating the above function would just work and allow temporaries to be moved using a notation like this:</p>
	
<pre class="programlisting">
  std::string(&quot;temporary on the&quot;).move()</pre>

<p>Note that so far there is no use of C++11 at all! The class template <code>movable_ref&lt;X&gt;</code> can be used with pre-C++11 compilers to move objects. There is the small caveat that it doesnâ€™t allow moving objects in return statements but with reasonable compilers there isnâ€™t much need for that as theyâ€™ll use copy-elision with carefully written functions anyway.</p>

<p>Of course, we wouldnâ€™t like this approach as it is a bit clumsy. Especially for temporaries it requires too much work! Also, the compiler can actually automatically tell whether an object can be moved or needs to be copied in many cases: if the object wasnâ€™t given a name, it can be moved as there is no way for the object to be accessed otherwise (well, the object could register itself somewhere but a class supporting moving is well-advised not to do so). Apart from unnamed objects there are also a few other cases when the compiler knows that the object can be safely moved. For example, when a named variable is returned from a function it can be moved:</p>

<pre class="programlisting">
  T f() {
    T value(...);
    // ...
    return value;
  }</pre>

<p>Note that the C++ standard considers moving <code>value</code> for the above function but will use copying if the return statement is written like this:</p>

<pre class="programlisting">
  return (value);</pre>

<p>In cases where it is known that an object wonâ€™t be used the compiler could generate the call to <code>move()</code> implicitly and yield a <code>movable_ref&lt;X&gt;</code>. It turns out this is nearly what happens! Instead of using the type <code>movable_ref&lt;X&gt;</code> the compile uses a type which matches the declaration <code>X&amp;&amp;</code> where <code>X</code> is not a deduced type (Iâ€™m using <code>X</code> instead of <code>T</code> to indicate that <code>X</code> is not a deduced type; <code>T</code> tends to be used for template parameters and is often deduced), i.e., it uses rvalue references. Before diving into more details of rvalue references note that the notation <code>movable_ref&lt;X&gt;</code> can be used interchangeably for <code>X&amp;&amp;</code> assuming the following using alias is visible:</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  using movable_ref = 
    std::add_rvalue_reference_t&lt;T&gt;;</pre>

<p>The interesting aspect of this <code>using</code> alias is that it allows code written in terms of <code>
movable_ref&lt;X&gt;</code> to be used both with a C++03 and a C++11 (or later) compiler. With a few support functions the identical code can be used to move objects! This yields a neat migration path for libraries which need to compile with both new and old compilers. The main flaw of this idea is that it is presented in 2015 and not, at least, 5 years ago. However, better late than never: it may still help some C++ users who havenâ€™t migrated off C++03 compilers.</p>

<p>Using <code>std::add_rvalue_reference_t&lt;X&gt;</code> in the definition of <code>movable_ref</code> instead of <code>X&amp;&amp;</code> has the advantage of preventing deduction of <code>X</code>. This nearly makes the using alias useful in general in C++11 rather than just for libraries which need to compile with both C++03 and later versions. The main danger is that using <code>std::movable_ref&lt;X&gt;&amp; x</code> is legal and looks as if <code>x</code> would be a reference to an object which can be moved from but it isnâ€™t. Instead the references are collapsed and the notation simply yields a <code>X&amp;</code>.</p>

<h2>rvalue references</h2>

<p>Now letâ€™s have a look at rvalue references. When you have got a <code>X&amp;&amp; </code>for some non-reference type <code>X</code>, e.g. <code>std::string&amp;&amp;</code>, you have got a reference which can only be bound to something which can be moved from. Either there are rules allowing the compiler to implicitly consider the object movable or the user has used a cast to have an lvalue look like an rvalue reference, e.g.:</p>

<pre class="programlisting">
  std::string     s(&quot;lvalue&quot;);
  std::string&amp;&amp; r = static_cast&lt;std::string&amp;&amp;&gt;(s);</pre>

<p>Using <code>std::move(s)</code> is just another way to write the cast above: <code>std::move()</code> is specified to deduce the argument type and do the cast.</p>

<p>A declaration even when using an rvalue reference, e.g., <code>r</code> in the above code, introduces an entity with a name. Since it has a name using <code>r</code> yields an lvalue! That is, the compiler wonâ€™t allow moving from the referenced object. The name <em>rvalue reference</em> derives from the kind of entities which can be bound to this sort of reference: rvalue references only allow binding objects which are about to go away or which are made to look as if that is the case with a cast. The compiler wonâ€™t allow binding an lvalue to an rvalue reference without a cast.</p>

<p>The net effect of these rules is that using <code>X&amp;&amp; x</code> as part of a function signature indicates that the function was called with an object which can be moved from and it is OK to change the state of <code>x</code>. The typical change is to move the content, i.e., to transfer resources from <code>x</code> to another object.</p>

<p>According to the core language this transfer can leave the object in some arbitrary state as long as it is safe to call the destructor on the object. However, the standard library mandates that the respective class invariants are retained for the moved-from object when using move construction or move assignment.</p>

<h2>Forwarding references</h2>

<p>Sadly, when you see a name declared as <code>T&amp;&amp; t</code> the object referenced by <code>T</code> cannot necessarily be moved! More specifically, if <code>T</code> is used to deduce the type the meaning of <code>T&amp;&amp;</code> is entirely different! For example, assume you have the class template in Listing 3.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;typename X&gt;
struct example {
  template &lt;typename T&gt;
  static void f(X&amp;&amp; x, T&amp;&amp; t) {
    // ...
  }
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>The type for <code>x</code> is not deduced. That is, <code>x</code> is a reference to a movable object of the template argument <code>X</code> specified to instantiate the class template <code>example</code>. On the other hand, the type <code>T</code> for <code>t</code> can be deduced based on the arguments given to <code>f()</code>. Listing 4 contains a few examples on how <code>f()</code> could be called and what the type <code>T</code> becomes.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
std::string       s(&quot;mutable&quot;);
std::string const c(&quot;immutable&quot;);
example&lt;int&gt;::f(int(1), s);
  // T == std::string&amp;
example&lt;int&gt;::f(int(2), c);
  // T == std::string const&amp;
example&lt;int&gt;::f(int(2), std::string(&quot;tmp&quot;));
  // T == std::string
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>When replacing <code>T</code> in the function template <code>f()</code> with <code>std::string&amp;</code> i.e., when instantiating <code>f()</code> for the type <code>std::string</code> the second argument type becomes <code>std::string&amp; &amp;&amp;</code>. This odd-looking type doesnâ€™t exist as the references are <em>collapsed</em>: if there are multiple reference qualifiers on a type, they get collapsed so there is only one reference qualifier:</p>

<ul>	
	<li><code>&amp; &amp;&amp;</code> becomes <code>&amp;</code></li>
	<li><code>&amp;&amp; &amp;</code> becomes <code>&amp;</code></li>
	<li><code>&amp;&amp; &amp;&amp;</code> becomes <code>&amp;&amp;</code></li>
</ul>

<p>That is, depending on how <code>f()</code> is called, <code>t</code> may be an lvalue reference or it may be an rvalue reference. Just because the argument is spelled as <code>T&amp;&amp;</code> and looks like an rvalue reference, it isnâ€™t necessarily one. Unconditionally trying to move from <code>t</code> would, thus, likely yield incorrect behavior.</p>

<p>Independent of how <code>f()</code> is called, <code>t</code> will be considered to be an lvalue. It always has a name and the compiler will not move from a named object implicitly unless the name is about to go away. If you want to potentially move an argument whose type was deduced, youâ€™d use <code>std::forward&lt;T&gt;(t)</code>: depending on the explicit template argument type <code>T</code> the function argument <code>t</code> will be cast to a suitable reference type: if <code>T</code> is not an lvalue reference type, the function yields a <code>T&amp;&amp;</code>. Otherwise the function yields the type <code>T</code>.</p>

<p>Since it is a bit awkward to talk about a <code>T&amp;&amp;</code> where the <code>T</code> is deduced, there needs to be a name. Scott Meyers refers to these references as <em>universal references</em>. The C++ standard defines the term <em>forwarding reference</em> for the same entities. I think this term describes what these entities are doing better.</p>

<h2>auto and &amp;&amp;</h2>

<p>The rules for the type deduced when using <code>auto</code> are identical to the rules used with deduced arguments for function templates. Thus, youâ€™ll get the following:</p>

<ul>
	<li><code>auto v = expr;</code> declares <code>v</code> to have the value type of the expression <code>expr</code> and the result of <code>expr</code> will be copied into <code>v</code> (of course, the copy can possibly be elided).</li>
	
	<li><code>auto&amp; r = expr;</code> declares <code>r</code> as an lvalue reference to the result of <code>expr</code> which assumes that <code>expr</code> indeed yields an lvalue.</li>
	
	<li><code>auto const&amp; c = expr;</code> declares <code>c</code> to a const lvalue reference to the result of <code>expr</code>. If <code>expr</code> doesnâ€™t yield an lvalue but a temporary, the life-time of the temporary gets expanded until <code>c</code> goes out of scope.</li>
	
	<li><code>auto&amp;&amp; s = expr;</code> declares <code>s</code> to be some reference to the result    of <code>expr</code>. If <code>expr</code> yields a value <code>s</code> will be an rvalue reference to the temporary whose life-time gets expanded until <code>s</code> goes out of scope. Otherwise <code>s</code> will be a reference to the reference yielded by <code>expr</code>.</li>
</ul>

<p>Similar to the use in function templates whether <code>s</code> can be moved from depends on how <code>s</code> actually happens to be declared despite the use of <code>&amp;&amp;</code>. That is, with names declared using <code>auto&amp;&amp;</code> you wouldnâ€™t use <code>std::move()</code>. Instead you would use <code>std::forward()</code> with a somewhat ugly-looking type:</p>

<pre class="programlisting">
  std::forward&lt;decltype(s)&gt;(s)</pre>

<p>Of course, spelling out the actual type may be a lot more ugly than <code>decltype(s)</code>.</p>

<p>Since we are on the topic of <code>auto</code> declarations: do <strong>not</strong> use range-based <code>for</code> loops using a variable declared as a plain <code>auto</code> unless you know that the value type of the iterator is a type which can be efficiently copied and you donâ€™t need to mutate the elements. Otherwise you are much better off to use <code>auto</code> with a reference qualifier. As a default it is reasonable to use <code>auto&amp;&amp;</code>:</p>

<pre class="programlisting">
  for (auto&amp;&amp; v: container) { ... }</pre>

<p>When the elements are only read you may want to explicitly indicate that the elements are not mutated in which case <code>auto const&amp;</code> is the way to go. Similarly, if you know you are going to mutate the elements you may want to explicitly indicate that using <code>auto&amp;</code>.</p>

<h2>Summary</h2>

<p>C++ uses the notation <code>T&amp;&amp;</code> for two entirely unrelated things:</p>

<ul>
	<li>If <code>T</code> is deduced <code>T&amp;&amp;</code> just means that an object is referenced and the type of <code>T</code> indicates whether the referenced object can be moved from.</li>
	
	<li>If <code>T</code> is not deduced <code>T&amp;&amp;</code> indicates that the referenced objects can be moved from unconditionally.</li>
</ul>

<p>To support move semantics using pre-C++11 compilers a class template can be used to indicate that an entity is movable. With a corresponding using alias and a few access functions the same notation can be used for rvalue references in C+11 providing a migration path.</p>

<h2>Reference and further reading</h2>

<p class="bibliomixed"><a id="[Nethack]"></a>[Nethack]  <a href="http://www.nethack.org/">http://www.nethack.org/</a></p>

<p>For further reading on this topic see one of these:</p>

<p class="bibliomixed">Thomas Beckerâ€™s articles: <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"><em>Effective Modern C++</em>, Scott Meyers, Item 24</p>

<p class="bibliomixed">Github: <a href="https://github.com/bloomberg/bde/blob/master/groups/bsl/bslmf/bslmf_movableref.h">https://github.com/bloomberg/bde/blob/master/groups/bsl/bslmf/bslmf_movableref.h</a></p>

<p class="bibliomixed">Scott Meyers. â€˜Universal references in C++11â€™ <em>Overload</em>, 20(111):8:12, October 2012. </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
