title: "Downcasting" unique_ptr<Base> to unique_ptr<Derived>
body: <p>I have a series of factories that return <code>unique_ptr&lt;Base&gt;</code>. Under the hood, though, they are providing pointers to various derived types, i.e <code>unique_ptr&lt;Derived&gt;</code>, <code>unique_ptr&lt;DerivedA&gt;</code>, <code>unique_ptr&lt;DerivedB&gt;</code>etc.</p>
  
  <p>Given <code>DerivedA : Derived</code> and <code>Derived : Base</code> we'd have:</p>
  
  <pre><code>unique_ptr&lt;Base&gt; DerivedAFactory() {
      return unique_ptr&lt;Base&gt;(new DerivedA);
  }
  </code></pre>
  
  <p>What I need to do is to "cast" the pointer from the returned <code>unique_ptr&lt;Base&gt;</code> to some derived level (not necessarily the original internal one). To illustrate in pseudo code:</p>
  
  <pre><code>unique_ptr&lt;Derived&gt; ptr = static_cast&lt;unique_ptr&lt;Derived&gt;&gt;(DerivedAFactory());
  </code></pre>
  
  <p>I'm thinking of doing this by releasing the object from the <code>unique_ptr</code>, then using a function that casts the raw pointer and reassigns that to another <code>unique_ptr</code> of the desired flavor (the <code>release</code> would be explicitly done by the caller prior to the call):</p>
  
  <pre><code>unique_ptr&lt;Derived&gt; CastToDerived(Base* obj) {
      return unique_ptr&lt;Derived&gt;(static_cast&lt;Derived*&gt;(obj));
  }
  </code></pre>
  
  <p>Is this valid, or is / will there be something funky going on?</p>
  
  <hr>
  
  <p><em>PS. There is an added complication in that some of the factories reside in DLLs that are dynamically loaded at run-time, which means I need to make sure the produced objects are destroyed in the same context (heap space) as they were created. The transfer of ownership (which typically happens in another context) must then supply a deleter from the original context. But aside from having to supply / cast a deleter along with the pointer, the casting problem should be the same.</em></p>