title: how can i move std::unique_ptr for constructor argument?
body: <p>My aim is to be able to create an object with a different kind of member object of from same class family; in <code>Java</code> it seems like this:</p>
  
  <pre><code>public class Interface {
      public void test();
  }
  
  public class MyImpl1 implements Interface {
      @Override
      public void test() {System.out.println("I am impl 1");}
  }
  
  public class MyImpl2 implements Interface {
      @Override
      public void test() {System.out.println("I am impl 2");}
  }
  
  public class A {
      public A(Interface myinter) {
          _myinter = myinter;
      }
  
      Interface _myinter;
  }
  </code></pre>
  
  <p>So that I can create an object with different implementation:</p>
  
  <pre><code>A a(new MyImpl1());
  </code></pre>
  
  <p>or</p>
  
  <pre><code>A a(new MyImpl2());
  </code></pre>
  
  <p>(Sorry if there is syntax error in this botched code, it is just to explain what I want)</p>
  
  <p>So, in C++ I think I would implement this with smart pointer to benefit from RAII. Thus, I wrote <a href="http://ideone.com/LuLxWN" rel="nofollow">this</a> code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  
  using namespace std;
  
  struct Interf {
      virtual void test() {cout &lt;&lt; "I am Interf" &lt;&lt; endl;}
  };
  
  struct A {
      A(std::unique_ptr&lt;Interf&gt; e) : _e(std::move(e)) {}
  
      std::unique_ptr&lt;Interf&gt; _e;
  
      void test() {_e-&gt;test();}
  };
  
  struct Impl : public Interf {
      void test() {cout &lt;&lt; "I am Impl;" &lt;&lt; endl;}
  };
  
  int main()
  {
      std::unique_ptr&lt;Interf&gt; b(new Impl);
  
      A a(std::move(b));
  
      a.test();
  
      cout &lt;&lt; "fine!" &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <ul>
  <li><p>It seems to me working. But, is this a correct way to implement it, or there are errores, or better practices?</p></li>
  <li><p>Also, in this code, I am not sure if I needed to use <code>std::move</code> twice. Is this the correct way to pass <code>unique_ptr</code> to constructor?</p></li>
  <li><p>Another thing I did not understand is why this code does not compile if I remove <code>_e(std::move(e))</code> from memberwise init list and put inside the constructor; some one please could also explain what is going on here?</p></li>
  </ul>
  
  <p>.</p>
  
  <pre><code>struct A {
      A(std::unique_ptr&lt;Interf&gt; e) {
          _e(std::move(e));
      }
      ...
  };
  </code></pre>