    <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  :: auto_value: Transfer Semantics for Value Types</title>
        <link>https://members.accu.org/index.php/articles/1423</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 + Design of applications and programs + Overload Journal #81 - Oct 2007</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/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c67/">Design</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/c232/">81</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+67+232/">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;auto_value: Transfer Semantics for Value Types</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 07 October 2007 11:56:00 +01:00 or Sun, 07 October 2007 11:56:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;In his quest to pass around values efficiently, Richard Harris concludes by looking at ways of transferring ownership, now and in the future.</p>
<p><strong>Body:</strong>&nbsp;<p>Last time we took a look at string and discussed the implications of the copy-on-write, or COW, optimisation. I concluded that despite its many shortfalls, I was unwilling to dismiss this type of optimisation out of hand.
  </p><p>
    This time, I'll explain why.
  </p><h2>
    auto_string
  </h2><p>
    Recall that it's <tt class="code">auto_ptr</tt> rather than <tt class="code">shared_ptr</tt> that is designed to manage ownership transfer. So, why not consider <tt class="code">auto_ptr</tt> rather than <tt class="code">shared_ptr </tt>semantics to eliminate the copy?
  </p><p>
    Let's look at a slightly different definition of <tt class="code">string</tt> (Listing 1).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    class string
    {
    public:
      typedef char         value_type;
      typedef char *       iterator;
      typedef char const * const_iterator;
      typedef size_t       size_type;
      //...

      string();
      string(const char *s);
      string(const string &amp;s);
      string(const auto_string &amp;s);

      string &amp; operator=(const string &amp;s);
      string &amp; operator=(const auto_string &amp;s);
      string &amp; operator=(const char *s);

      auto_string release();

      const_iterator begin() const;
      const_iterator end() const;
      iterator begin();
      iterator end();
      //...

    private:
      size_type size_;
      scoped_array&lt;char&gt; data_;
    };
  </pre>
  </td></tr><tr><td class="title">Listing 1</td></tr></table>
  <p>
    Here, the data is stored in a scoped_array (like <tt class="code">scoped_ptr </tt>but uses <tt class="code">delete[]</tt>) rather than a <tt class="code">shared_array</tt> and we've picked up a few extra functions, all of which refer to a new type, <tt class="code">auto_string</tt>.
  </p><p>
    Let's have a look at the definition of <tt class="code">auto_string</tt> (Listing 2).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    class auto_string
    {
      friend class string;

      auto_string(string::size_type n,
                  const auto_array&lt;char&gt; &amp;s) throw();

      string::size_type size_;
      auto_array&lt;char&gt; data_;
    };
  </pre>
  </td></tr><tr><td class="title">Listing 2</td></tr></table>
  <p>
    So, <tt class="code">auto_string</tt> is simply a wrapper for an <tt class="code">auto_array</tt> (which also uses <tt class="code">delete[]</tt>) that hides its data from everything but <tt class="code">string</tt>.
  </p><p>
    This gives us an explicit mechanism for stating that we wish to transfer ownership of a <tt class="code">string</tt>, through the <tt class="code">release</tt> member function (Listing 3).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_string
      string::release()
      {
        return auto_string(size_, data_.release());
      }
  </pre>
  </td></tr><tr><td class="title">Listing 3</td></tr></table>
  <p>
    The constructor and assignment operator can now be overloaded to take advantage of the fact that we are transferring ownership (Listing 4).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    string::string(const auto_string &amp;s) :
                    size_(s.size_), data_(s.data_)
    {
    }

    string &amp;
    string::operator=(const auto_string &amp;s)
    {
      string tmp(s);
      swap(tmp);
      return *this;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 4</td></tr></table>
  <p>
    Now, when we assign an <tt class="code">auto_string</tt> returned from a function to a <tt class="code">string</tt> (Listing 5), we have the sequence of events shown in Listing 6 and at no point is the string data copied.
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_string
    f()
    {
      string result(&quot;hello, world&quot;);
      return result.release();
    }

    void
    g()
    {
      string s;
      s = f();
    }
  </pre>
  </td></tr><tr><td class="title">Listing 5</td></tr></table>
<br/>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    call g
    default construct s;

    call f
    construct &quot;hello, world&quot; into result
    transfer s into temporary auto_string
    transfer temporary auto_string into return value
    exit f

    transfer auto_string into tmp
    swap data with tmp
    exit g
  </pre>
  </td></tr><tr><td class="title">Listing 6</td></tr></table>
<p>
    The advantage this has over the <tt class="code">shared_array</tt> version is that at every step of copy construction or assignment, the string data is owned by one and only one object. In other words, we no longer have aliasing of the data and consequently don't have to deal with the headaches that that causes.
  </p><p>
    Of course, since the compiler can optimise the copy away anyway, all we have succeeded in doing is to create a slightly better version of a completely pointless optimisation.
  </p><p>
    Well, not quite.
  </p><p>
    Thank you for your patience, by the way.
  </p><h2>
    vector
  </h2><p>
    There is, in fact, another benefit to explicit lifetime control but this is much better illustrated with a class representing a mathematical vector.
  </p><p>
    To start, let's have a brief recap of <tt class="code">valarray</tt>. Just kidding - see Listing 7.
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    class vector
    {
    public:
      typedef double         value_type;
      typedef double *       iterator;
      typedef double const * const_iterator;
      typedef size_t         size_type;
      //...

      vector();
      vector(const vector &amp;v);
      vector(const auto_vector&lt;T&gt; &amp;v);
      explicit vector(size_t n);

      vector &amp; operator=(const vector &amp;v);
      vector &amp; operator=(const auto_vector &amp;v);

      auto_vector release();

      const_iterator begin() const;
      const_iterator end() const;
      iterator begin();
      iterator end();
      //...
      vector&amp; operator+=( const vector&amp; v );
      //...

    private:
      size_type size_;
      scoped_array&lt;double&gt; data_;
    };
  </pre>
  </td></tr><tr><td class="title">Listing 7</td></tr></table>
  <p>
    The principal difference between this and a <tt class="code">std::vector&lt;double&gt;</tt> is that we want to support mathematical vector operations.
  </p><p>
    Let's use vector addition as an example (Listing 8).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    vector
    operator+(const vector &amp;l, const vector &amp;r)
    {
      vector tmp(l);
      tmp += r;
      return tmp;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 8</td></tr></table>
  <p>
    Now this isn't the most efficient implementation, creating an uninitialised vector and filling it with the result of the addition would have 3n read and write operations whereas this has 4n. Still, it does enable us to reuse the in-place addition operator.
  </p><p>
    Note that we are assuming that both in-place addition and out-of-place addition require 2n operations, with out-of-place addition incurring a further n to copy the results. Strictly speaking this is not the case since the processor must make 3n reads and writes from main memory in both cases.
  </p><p>
    However, for many processors in-place addition will make much better use of the processor cache and as a result will generally be more efficient.
  </p><p>
    A few crude experiments with my compiler supported this, showing that out-of-place addition did indeed take approximately 1.5 times as long as in-place addition, so we shall maintain these complexity assumptions as a convenient fiction.
  </p><p>
    We can effectively address the efficiency concern when <tt class="code">l</tt> is bound to a function return value by redefining the operator as shown in Listing 9.
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    vector
    operator+(vector l, const vector &amp;r)
    {
      l += r;
      return l;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 9</td></tr></table>
  <p>
    Now we are exploiting copy elision to reduce the number of reads and writes to 2n, even better than if we were to use an uninitialised vector to store the result.
  </p><p>
    Unfortunately, we'll still pay for the extra copy when <tt class="code">l</tt> is a variable. This is especially irritating if <tt class="code">r</tt> is a function return value and hence a candidate for in-place addition. Since reference to <tt class="code">T</tt> and value of <tt class="code">T</tt> are afforded the same status during function overload resolution we can't use overloading to address this. Unless we use a different type for our temporaries. Like <tt class="code">auto_vector</tt>, for example (Listing 10).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_vector operator+(const vector &amp;l,
                          const vector &amp;r);
    auto_vector operator+(const auto_vector &amp;l,
                          const vector &amp;r);
    auto_vector operator+(const vector &amp;l,
                          const auto_vector &amp;r);
    auto_vector operator+(const auto_vector &amp;l,
                          const auto_vector &amp;r);
  </pre>
  </td></tr><tr><td class="title">Listing 10</td></tr></table>
  <p>
    The implementation of each overload will look like our first version, except that we will prefer to construct the temporary from an <tt class="code">auto_vector</tt> whenever possible, so that we can avoid copying one of the arguments (Listing 11).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_vector
    operator+(const auto_vector &amp;l, const vector &amp;r)
    {
      vector tmp(l);
      tmp += r;
      return tmp.release();
    }
  </pre>
  </td></tr><tr><td class="title">Listing 11</td></tr></table>
  <p>
    So the long awaited advantage of this approach is that it allows us to indicate when we no longer care what happens to an object, which we can exploit both for transfer initialisation and for transforming out-of-place operations into in-place operations.
  </p><p>
    Note that by returning <tt class="code">auto_vectors</tt> from the addition operators we can eliminate the construction of a series of temporaries in a compound expression (Listing 12).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_vector
    f()
    {
      vector x;
      //...
      return x.release();
    }

    auto_vector
    g()
    {
      vector x;
      //...
      return x.release();
    }

    auto_vector
    h()
    {
      vector x;
      //...
      return x.release();
    }

    void
    i()
    {
      vector sum = f()+g()+h();
    }
  </pre>
  </td></tr><tr><td class="title">Listing 12</td></tr></table>
  <p>
    With the original implementation of addition, the cost of the summation would have been:
  </p>
		<ul><li>
    2 copies to temporary values at 2n read/writes each
  </li><li>
    2 in-place additions at 2n read/writes each
  </li></ul><p>
    This gives us a grand total of 8n read/write operations.
  </p><p>
    Recall that if we were willing to forego reuse of the in-place addition operator, we could remove one of the read/write operations from creating each of the temporary values, making the cost of summation:
  </p>
		<ul><li>
    2 additions at 2n read/writes each
  </li><li>
    2 copies to temporary values at n read/writes each
  </li></ul><p>
    Reducing the total to 6n read/write operations.
  </p><p>
    With <tt class="code">auto_vector</tt>, however, this becomes:
  </p>
		<ul><li>
    5 transfers to temporary values at O(1) read/writes each
  </li><li>
    2 in-place additions at 2n read/writes each
  </li></ul><p>
    Giving us a final total of 4n + O(1) read/write operations. Not too shabby.
  </p><p>
    There are two principal disadvantages to this approach.
  </p><p>
    Firstly we have to write overloaded versions of every function and secondly we have to write a lot of boilerplate code.
  </p><p>
    Don't we?
  </p><p>
    The crux of the first problem is that we only want to overload a function if there is an advantage to us to do so. In other words, we only want to overload functions which can exploit the reuse of temporary objects. A lot of functions can't and we really don't want to make work for ourselves by having to overload them. See Listing 13, for example.
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    double
    abs(const vector &amp;v)
    {
      double sum_square = 0.0;
      vector::const_iterator first = v.begin();
      vector::const_iterator last  = v.end();

      while(first!=last)
      {
        sum_square += *first * *first;
        ++first;
      }

      return sqrt(sum_square);
    }
  </pre>
  </td></tr><tr><td class="title">Listing 13</td></tr></table>
  <p>
    Thankfully, in such cases it's perfectly OK to pass an <tt class="code">auto_vector</tt> instead of a <tt class="code">vector</tt>. This is because the compiler is allowed to bind a const reference to a temporary that is the result of a conversion. And a <tt class="code">vector</tt> can be conversion constructed from an <tt class="code">auto_vector</tt>.
  </p><p>
    The second problem is a little trickier to resolve.
  </p><h2>
    auto_value
  </h2><p>
    What we really need is a class that can manage the value transfer semantics for us. Much like <tt class="code">auto_ptr</tt> does for pointers.
  </p><p>
    The class definition is actually pretty straightforward (Listing 14).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    template&lt;typename X&gt;
    class auto_value
    {
    public:
      typedef X element_type;

      explicit auto_value(X &amp;x) throw();
      auto_value(const auto_value &amp;x) throw();

      auto_value &amp; operator=(const auto_value &amp;x) throw();

      X &amp; get() const throw();

    private:
      mutable X x_;
    };
  </pre>
  </td></tr><tr><td class="title">Listing 14</td></tr></table>
  <p>
    It's the implementation that's the problem.
  </p><p>
    What we really need to find is a generic way to transfer ownership of the controlled value to and from the <tt class="code">auto_value</tt>.
  </p><p>
    Fortunately, for most of the types we are interested in, one already exists in <tt class="code">swap</tt>.
  </p><p>
    Let's see how we can use it to implement the member functions of  <tt class="code">auto_value</tt> (Listing 15).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(X &amp;x)
    {
      x_.swap(x);
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(const auto_value &amp;x)
    {
      x_.swap(x.get());
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt; &amp;
    auto_value&lt;X&gt;::operator=(const auto_value &amp;x)
    {
      x_.swap(x.get());
      return *this;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 15</td></tr></table>
  <p>
    The chief problem with using <tt class="code">swap</tt> rather than transferring the state directly is that we have to default construct a value before we can swap the transferred value in. This pretty much limits <tt class="code">auto_value</tt> to types with relatively inexpensive default constructors.
  </p><p>
    Note that we've supplied an explicit transfer constructor for the original value. This is more in keeping with the <tt class="code">auto_ptr</tt> interface and removes the need to add a <tt class="code">release</tt> method to the class.
  </p><p>
    There's not much we can do about the conversion constructor and assignment operator that need to be implemented in the class itself.
  </p><p>
    Fortunately, these are pretty simple (Listing 16).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    X::X(const auto_value&lt;X&gt; &amp;x)
    {
      swap(x.get());
    }

    X &amp;
    X::operator=(const auto_value&lt;X&gt; &amp;x)
    {
      swap(x.get());
      return *this;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 16</td></tr></table>
  <p>
    We could make it easier still if we were to abandon our sensibilities and define these functions inline using a macro.
  </p><p>
    I can't quite bring myself to write it though.
  </p><p>
    There's only one thing left that's really lacking from the <tt class="code">auto_value</tt> interface and that's <tt class="code">operator.</tt>. This would allow us to use the <tt class="code">auto_value</tt> as a proxy for calls to the transferred object's member functions in the same way that <tt class="code">operator*</tt> and <tt class="code">operator-&gt;</tt> do for <tt class="code">auto_ptr</tt>.
  </p><p>
    Shame it doesn't exist.
  </p><p>
    Fortunately, there's another way to do this.
  </p><p>
    That other way is inheritance. If our <tt class="code">auto_value</tt> were to inherit from rather than contain the value it controls, it would trivially be able to act as a proxy.
  </p><p>
    Let's have a look at the changes we need to make (Listing 17).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    template&lt;typename X&gt;
    class auto_value : public X
    {
    public:
      typedef X element_type;

      explicit auto_value(X &amp;x) throw();
      auto_value(const auto_value &amp;x) throw();

      auto_value &amp; operator=(
         const auto_value &amp;x) throw();
    };
  </pre>
  </td></tr><tr><td class="title">Listing 17</td></tr></table>
  <p>
    The unfortunate side effect of this is that the <tt class="code">auto_value</tt> and the value it controls are now the same entity, and hence a const <tt class="code">auto_value</tt> implies a const value. Now, you'll recall that function return values can't be bound to non-const references and that <tt class="code">swap</tt> is a non-const member function that has a non-const reference argument.
  </p><p>
    That's right. We can't use <tt class="code">swap</tt> to implement our transfer semantics any more. Not unless we cast away the constness, that is (Listing 18).
  </p>
    <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(X &amp;x)
    {
      swap(x);
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(const auto_value &amp;x)
    {
      swap(const_cast&lt;auto_value &amp;&gt;(x));
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt; &amp;
    auto_value&lt;X&gt;::operator=(const auto_value &amp;x)
    {
      swap(const_cast&lt;auto_value &amp;&gt;(x));
      return *this;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 18</td></tr></table>
<p>
    Pretty slick, I'm sure you'll agree.
  </p><p>
    There's just one tiny little problem with this code. Hardly even worth mentioning.
  </p><p>
    It's implementation-defined whether or not this will invoke the dreaded undefined behaviour.
  </p><p>
    There's a clause in the C++ standard stating that compilers are allowed to bind const references to function returns in one of two ways. They can either bind to the value itself, or they can copy it into a const value and bind to that.
  </p><p>
    Seems innocuous enough, but there's another clause that states that trying to modify a const value results in undefined behaviour. Which we all know could mean anything from doing exactly what you expect to washing away our coding sins with the cleansing fire of a thermonuclear explosion.
  </p><p>
    I can't think of any compiler vendors who'd go for the latter option though.
  </p><p>
    Well, on reflection...
  </p><p>
    Actually, no, not even them.
  </p><h2>
    transfer
  </h2><p>
    Fortunately we can avoid invoking undefined behaviour if we are willing to force users of <tt class="code">auto_value</tt> to do a little additional work.
  </p><p>
    Specifically, we'll need them to implement an ownership transfer mechanism that will work for const objects. Let's call it <tt class="code">transfer</tt> and have a look at how vector might implement it (Listing 19).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
<span style="color: grey;"> class vector
 {
 public:
   typedef double             value_type;
   typedef double *           iterator;
   typedef double const *     const_iterator;
   typedef size_t             size_type;</span>
      typedef auto_value&lt;vector&gt; auto_vector;
      //...
<span style="color: grey;">
   vector();
   vector(const vector &amp;v);
   vector(const auto_vector&lt;T&gt; &amp;v);
   explicit vector(size_t n);

   vector &amp; operator=(const vector &amp;v);
   vector &amp; operator=(const auto_vector &amp;v);

   const_iterator begin() const;
   const_iterator end() const;
   iterator begin();
   iterator end();
      //...
</span>
    protected:
      void transfer(const auto_vector &amp;v) const;
<span style="color: grey;">
 private:</span>
      mutable <span style="color: grey;">scoped_array&lt;double&gt; data_;
 };</span>
  </pre>
  </td></tr><tr><td class="title">Listing 19</td></tr></table>
  <p>
    Firstly, we've added a typedef that defines <tt class="code">auto_vector</tt> as an <tt class="code">auto_value</tt> of vector. Secondly, we've added a protected member function transfer to manage the ownership transfer. Finally, we've made the <tt class="code">data_ member</tt> mutable so that the const transfer function can affect it.
  </p><p>
    A protected member function? Yeah, yeah, I know.
  </p><p>
    If you're really bothered by it you can grant friendship to <tt class="code">auto_value&lt;vector&gt;</tt> and make it private instead. The point is that the <tt class="code">transfer</tt> member must be accessible by the derived <tt class="code">auto_value&lt;vector&gt;</tt>, but probably shouldn't be public since it will violate the perfectly reasonable expectation that const objects won't change.
  </p><p>
    Some of you may also balk at the thought of forcing client classes to make their state mutable.
  </p><p>
    Well, I can give two reasons why you shouldn't worry too much about it.
  </p><p>
    Firstly, we have no choice. By making the state mutable we are allowed to change it even if the object is <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">really</span> const. This enables us to neatly side step the clause in the standard that allows compilers to copy a return value into a const object.
  </p><p>
    Secondly, it doesn't matter. Const methods are already allowed to change the state of the object.
  </p><p>
    You may find the second point a little surprising, so I'll elaborate.
  </p><p>
    The <tt class="code">vector</tt> class, like most container types, stores its state in a memory buffer. If you took a look at the definition of <tt class="code">scoped_array</tt>, you'd notice that the access member functions are all const, but return non-const pointers or references. This means that the elements of the array can be changed even when accessed through a const method. Whilst this may seem a little counter intuitive, it's exactly how a pointer data member would behave. They key point to note is that constness doesn't propagate through the pointer.
  </p><p>
    Namely:
  </p>
<pre class="programlisting">
      X * const x;
</pre><p>
    and:
  </p>
<pre class="programlisting">
      X const * const x;
</pre><p>
    do <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">not</span> mean the same thing. The former defines an immutable pointer to a mutable value and the latter an immutable pointer to an immutable value, and it is the former that is implicitly applied to pointer data members in a const member function.
  </p><p>
    The behaviour we've come to expect from our container classes, that const member functions will not change the value of any items in the container, is enforced by the programmer rather than the compiler. When implementing container classes we must always be careful not to change the state through const member functions since the compiler is unlikely to warn us that we are doing so. Making the state mutable therefore has little effect on the effort we must spend designing the class.
  </p><p>
    Now we're finished discussing the design choices, let's take a look at the implementation:
  </p>
<pre class="programlisting">

    void
    vector::transfer(const auto_value&lt;vector&gt; &amp;v) const
    {
      data_.swap(v.data_);
    }
</pre><p>
    So <tt class="code">transfer</tt> is actually just a <tt class="code">swap</tt> for const objects, which shouldn't be particularly surprising since we've been using <tt class="code">swap</tt> for ownership transfer from the start.
  </p><p>
    We'll need to provide new implementations of the conversion constructor and assignment operator used for ownership transfer (Listing 18).
  </p>
  <p>
    Again, these shouldn't be particularly surprising. We've just replaced the calls to <tt class="code">swap</tt> with calls to <tt class="code">transfer</tt>.
  </p><p>
    Finally, we need to rewrite the <tt class="code">auto_value</tt> member functions to make use of the <tt class="code">transfer</tt> function (Listing 19).
  </p>
  <p>
    Yet again, we have simply replaced the calls to <tt class="code">swap</tt> with calls to <tt class="code">transfer</tt>.
  </p><p>
    So, there we have it, a simple class implementing explicit ownership transfer that requires just a few trivial member functions and a relaxed attitude to constness in its client classes.
  </p><p>
    If we are willing to accept this compromise, <tt class="code">auto_value</tt> provides the same functionality as a custom made value transfer type with a lot less work.
  </p><p>
    Recalling the <tt class="code">auto_vector</tt> addition operators (Listing 20).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    vector::vector(const auto_value&lt;vector&gt; &amp;v)
    {
      transfer(v);
    }

    vector &amp;
    vector::operator=(const auto_value&lt;vector&gt; &amp;v)
    {
      transfer(v);
      return *this;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 20</td></tr></table>
  <p>
    We can implement these operators in the same way as before, by constructing a temporary vector from an <tt class="code">auto_vector</tt> argument (where there is one) and performing the addition in-place (Listing 21).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(X &amp;x)
    {
      transfer(x);
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt;::auto_value(const auto_value &amp;x)
    {
      transfer(x);
    }

    template&lt;typename X&gt;
    auto_value&lt;X&gt; &amp;
    auto_value&lt;X&gt;::operator=(const auto_value &amp;x)
    {
      transfer(x);
    }
  </pre>
  </td></tr><tr><td class="title">Listing 21</td></tr></table>
  <p>
    In fact, since the <tt class="code">auto_value</tt> copy constructor transfers ownership, we can further simplify these operators by passing the <tt class="code">auto_value</tt> arguments by value. For example:
  </p>
<pre class="programlisting">
      auto_vector operator+(auto_vector l,
                            const vector &amp;r);
</pre><p>
    Now, instead of transferring the <tt class="code">auto_vector</tt> into a temporary vector, we can exploit the fact that <tt class="code">auto_vector</tt> inherits from <tt class="code">vector</tt> to perform in-place addition directly (Listing 22), saving us a little bit of typing and a few calls to transfer.
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    typedef auto_value&lt;vector&gt; auto_vector;

    auto_vector operator+(const vector &amp;l,
                          const vector &amp;r);
    auto_vector operator+(const auto_vector &amp;l,
                          const vector &amp;r);
    auto_vector operator+(const vector &amp;l,
                          const auto_vector &amp;r);
    auto_vector operator+(const auto_vector &amp;l,
                          const auto_vector &amp;r);
  </pre>
  </td></tr><tr><td class="title">Listing 22</td></tr></table>
  <p>
    Once again, if we don't care about reusing temporaries we simply provide a single version of a function:
  </p>
<pre class="programlisting">
      double abs(const vector &amp;v);
</pre><p>
    As before, this function will work for both vectors and <tt class="code">auto_vectors</tt> although now this is because <tt class="code">auto_vector</tt> inherits from <tt class="code">vector</tt> and can therefore be bound directly to the reference.
  </p><h2>
    namespace mojo
  </h2><p>
    In his article 'Generic&lt;Programming&gt;: Move Constructors' (<i>Dr Dobb's Journal</i>, 2003), Alexandrescu describes the Mojo framework for automatically detecting temporaries and using move semantics for them.
  </p><p>
    By its very nature this technique must rely upon implicit, rather than explicit, conversion to transfer types and hence requires a little extra work to ensure that temporaries are bound to the correct transfer type.
  </p><p>
    The upshot of this is that three overloads, rather than two, must be provided for each function that exploits move semantics. Nevertheless, this is arguably a more sophisticated solution to the problem.
  </p><h2>
    T &amp;&amp;t
  </h2><p>
    To close, it's worth mentioning that the value transfer semantics we've worked so hard to implement are trivial using the above notation.
  </p><p>
    If you're wondering why on Earth I didn't just go ahead and use it instead of leading you down the garden path, it's because it isn't C++. Not yet.
  </p><p>
    The notation is for a new kind of reference proposed for the next version of C++, the rvalue reference.
  </p><p>
    The rvalue reference differs from the familiar reference (hereafter known as an lvalue reference) in eight ways. Paraphrasing the proposal slightly:
  </p>
		<ul><li>
    A non-const rvalue can bind to a non-const rvalue reference.
  </li><li>
    Overload resolution rules prefer binding rvalues to rvalue references and lvalues to lvalue references.
  </li><li>
    Named rvalue references are treated as lvalues.
  </li><li>
    Unnamed rvalue references are treated as rvalues.
  </li><li>
    The result of casting an lvalue to an rvalue reference is treated as an rvalue.
  </li><li>
    Where elision of copy constructor is currently allowed for function return values, the local object is implicitly cast to an rvalue reference.
  </li><li>
    Reference collapsing rules are extended to include rvalue references.
  </li><li>
    Template deduction rules allow detection of rvalue/lvalue status of bound argument.
  </li></ul><p>
    For the purpose of eliminating copies, behaviours 1-3 are of particular interest. Put simply, they mean that a non-const temporary <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">can</span> be bound to a reference type through which we can legally modify them. Specifically, we now have four kinds of reference (Listing 23).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_vector
    operator+(const auto_vector &amp;l, const vector &amp;r)
    {
      vector tmp(l);
      tmp += r;
      return auto_vector(tmp);
    }
  </pre>
  </td></tr><tr><td class="title">Listing 23</td></tr></table>
  <p>
    In the same way that a non-const object is preferentially bound to a non-const reference, an rvalue is preferentially bound to an rvalue reference and an lvalue is preferentially bound to an lvalue reference.
  </p><p>
    Given the following function signatures:
  </p>
<pre class="programlisting">
      f(T &amp;&amp;t);       //1
      f(T const &amp;&amp;t); //2
      f(T &amp;t);        //3
      f(T const &amp;t);  //4
</pre><p>
    and the following references:
  </p>
<pre class="programlisting">
      T &amp;&amp;t1;
      T const &amp;&amp; t2;
      T &amp; t3;
      T const &amp; t4;
</pre><p>
    The rules mean that:
  </p><p class="indented">
    t1 binds to overloads 1, 2, 3 and 4 in that order of preference
  </p><p class="indented">
    t2 binds to overloads 2 and 4 in that order of preference
  </p><p class="indented">
    t3 binds to overloads 3, 4, 1 and 2 in that order of preference
  </p><p class="indented">
    t4 binds to overloads 4 and 2 in that order of preference
  </p><p>
    The original justification for disallowing the binding of rvalues to non-const references was that it was generally a mistake to do so. Changing an object which is about to go out of scope and be destroyed will, after all, lose those changes.
  </p><p>
    This is especially nasty when the object in question is a temporary resulting from an implicit conversion (Listing 24).
  </p>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    auto_vector
    operator+(auto_vector l, const vector &amp;r)
    {
      l += r;
      return l;
    }
  </pre>
  </td></tr><tr><td class="title">Listing 24</td></tr></table>
<br/>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    //non-const reference to rvalue
    typedef T &amp;&amp;       Ref1;

    //const reference to rvalue
    typedef T const &amp;&amp; Ref2;

    //non-const reference to lvalue
    typedef T &amp;        Ref3;

    //const reference to lvalue
    typedef T const &amp;  Ref4;
  </pre>
  </td></tr><tr><td class="title">Listing 25</td></tr></table>
<br/>
  <table class="sidebartable"><tr><td>
  <pre class="programlisting">
    void f(long &amp;i);

    void g()
    {
      char c = 0;
      f(c); //oops
      //...
    }
  </pre>
  </td></tr><tr><td class="title">Listing 26</td></tr></table>
  <p>
    Since the character <tt class="code">c</tt> is promoted to a long with an implicit conversion, <tt class="code">f</tt> receives a reference to the temporary long that is the result of that conversion. The upshot of which is that, generally to the surprise and consternation of the programmer, <tt class="code">c</tt> never changes.
  </p><p>
    Move semantics, however, have brought to light a situation in which this is a valid thing to want to do. The new rvalue references provide a mechanism by which we can express that we deliberately wish to change the value of a temporary object whilst avoiding the original problem.
  </p><p>
    Specifically, overloading on non-const rvalue reference and const lvalue reference enables us to distinguish between destructively reusing a temporary object and non-destructively referring to a non-temporary object.
  </p><p>
    Which is, of course, exactly what we've been striving to achieve.
  </p><h2>
    article::~ article()
  </h2><p>
    So has this all been a tremendous waste of time?
  </p><p>
    I hope not.
  </p><p>
    Firstly, I hope that this has given you cause to think a little more about how you can exploit ownership control.
  </p><p>
    Secondly, I hope that you may find <tt class="code">auto_value</tt>, or something like it, a useful stop gap.
  </p><p>
    And finally, I hope that you've enjoyed it.
  </p><p>
    If not, I refer you to Harris's Addendum:
  </p>
		<p><span class="quote">
    Nyah, nyah. I can't hear you. </span></p><h2>
    #include
  </h2><p class="bibliomixed">
    [<a name="Alexandrescu2003"></a>Alexandrescu, 2003] Alexandrescu, 'Generic&lt;Programming&gt;: Move Constructors' (<i>Dr Dobb's Journal</i>, 2003).
  </p><p>
    [<a name="Hinnant2004"></a>Hinnant, 2004] Hinnant, Abrahams and Dimov, 'A Proposal to Add an Rvalue Reference to the C++ Language' (ISO/IEC JTC1/SC22/WG21 Document Number N1690, 2004).
  </p><p>
    With thanks to Kevlin Henney for his review of this article and Astrid Osborn, Keith Garbutt and Niclas Sandstrom for proof reading it.
  </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
