title: Casting between unique_ptr's in C++
body: <p>I have the following C++11 construct:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;memory&gt;
  
  class X {
  public:
          void f(void) { }
  };
  
  class Y : public X {
  public:
          void g(void) { }
  };
  
  class A {
  private:
          std::vector &lt;std::unique_ptr &lt;X&gt; &gt; xs;
  public:
          void addX(std::unique_ptr &lt;X&gt; &amp;ref) {
                  xs.push_back(std::move(ref));
          }
  };
  
  int main() {
          A a;
  
          std::unique_ptr &lt;Y&gt; y(new Y());
          y-&gt;f();
          y-&gt;g();
  
          std::unique_ptr &lt;X&gt; x(y.release());
          a.addX(x);
  
          return 0;
  }
  </code></pre>
  
  <p>In the main function I am trying to build an object of type Y and then add it to the vector of X objects of a. However, I can not directly say <code>a.addX(y)</code> as <code>std::unique_ptr &lt;Y&gt;</code> cannot be cast to <code>std::unique_ptr &lt;X&gt;&amp;</code>. This is why I came up with the workaround where I initialize another unique pointer, x, with the released internal pointer of y.</p>
  
  <p>Although this works, it doesn't seem like the best solution. Is there a better way of passing an object of type <code>std::unique_ptr&lt;Y&gt;</code> as an argument of type <code>std::unique_ptr&lt;X&gt;&amp;</code>?</p>
  
  <p>Thanks,
   - Stan</p>