title: Auto-cloning unique_ptr
body: <p><code>std::unique_ptr</code> has a deleted copy constructor, which means that if you have a <code>unique_ptr</code> in your class <code>Foo</code> as a data member then you must write your own copy constructor for <code>Foo</code> and manually deep-copy that member (even if the compiler-generated copy constructor would be fine for all other members).</p>
  
  <p>In order to be able to copy in a polymorphic way, the <code>clone()</code> method pattern can be used. Let's assume our objects have a clone method like this:</p>
  
  <pre><code>class Base {
      virtual std::unique_ptr&lt;Base&gt; clone() = 0;
  };
  </code></pre>
  
  <p>Foo looks like this now:</p>
  
  <pre><code>class Foo {
  public:
      ...
      Foo(Foo const&amp; other)
          : b(other.b-&gt;clone())
          , // init 10 more members that could otherwise be auto-copied just fine
            // with the automatically generated copy constructor
      {}
      ...
  
  private:
      std::unique_ptr&lt;Base&gt; b;
      //10 more data members
  
  };
  </code></pre>
  
  <p>Now, I found a way to auto-clone <code>Foo::b</code>, by writing a wrapper over <code>unique_ptr</code> that defines the copy constructor and assignment by calling <code>clone</code>.</p>
  
  <pre><code>template &lt;typename T&gt;
  class auto_cloned_unique_ptr
  {
  private:
      std::unique_ptr&lt;T&gt; up;
  
  public:
      // copy constructor
      auto_cloned_unique_ptr(auto_cloned_unique_ptr&lt;T&gt; const&amp; other)
          : up(other.up-&gt;clone()) {}
  
      // copy assignment
      auto_cloned_unique_ptr&lt;T&gt;&amp; operator =(auto_cloned_unique_ptr&lt;T&gt; const&amp; other)
      {
          this-&gt;up = other.up-&gt;clone();
          return *this;
      }
  
      auto_cloned_unique_ptr(std::unique_ptr&lt;T&gt; _up)
          : up(std::move(_up)) {}
  
      // Delegate everything else to unique_ptr
      auto_cloned_unique_ptr(auto_cloned_unique_ptr&lt;T&gt;&amp;&amp; other)
          : up(std::move(other.up)) {}
  
      auto_cloned_unique_ptr&lt;T&gt;&amp; operator =(auto_cloned_unique_ptr&lt;T&gt;&amp;&amp; other)
      {
          this-&gt;up = std::move(other.up);
          return *this;
      }
  
      auto operator *() const {return *up;}
      auto operator-&gt;() const {return up.operator-&gt;();}
      auto get() -&gt; const {return up.get();}
  
  };
  </code></pre>
  
  <p>Now if we use this we don't need to define our own copy constructor:</p>
  
  <pre><code>class Foo2 {
  public:
      ...
  
  private:
      auto_cloned_unique_ptr&lt;Base&gt; b;
      //10 more data members
  
  };
  </code></pre>
  
  <p>Is such an approach very much frowned upon (for using a non-standard wrapper over <code>unique_ptr</code>)?</p>