title: How do you move a unique_ptr out of an vector<unique_ptr<Foo>>?
body: <p>I would like to move a <code>unique_ptr&lt;Foo&gt;</code> out of a <code>vector&lt;unique_ptr&lt;Foo&gt;&gt;</code>. Consider my code:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;memory&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  class Foo {
  public:
    int x;
    Foo(int x): x(x) {};
    ~Foo() {
      cout &lt;&lt; "Destroy of id: " &lt;&lt; x &lt;&lt; "\n";
      x = -1;
    };
  };
  
  int main(int argc, char *argv[]) {
    auto foos = vector&lt;unique_ptr&lt;Foo&gt;&gt;();
    foos.push_back(unique_ptr&lt;Foo&gt;(new Foo(100)));
    foos.push_back(unique_ptr&lt;Foo&gt;(new Foo(101)));
    foos.push_back(unique_ptr&lt;Foo&gt;(new Foo(102)));
  
    // Print all
    cout &lt;&lt; "Vector size: " &lt;&lt; foos.size() &lt;&lt; "\n";
    for (auto i = foos.begin(); i != foos.end(); ++i) {
      cout &lt;&lt; (*i)-&gt;x &lt;&lt; "\n";
    }
  
    // Move Foo(100) out of the vector
    {
      auto local = move(foos.at(0));
      cout &lt;&lt; "Removed element: " &lt;&lt; local-&gt;x &lt;&lt; "\n";
    }
  
    // Print all! Fine right?
    cout &lt;&lt; "Vector size: " &lt;&lt; foos.size() &lt;&lt; "\n";
    for (auto i = foos.begin(); i != foos.end(); ++i) {
      cout &lt;&lt; (*i)-&gt;x &lt;&lt; "\n";
    }
  
    return 0;
  }
  </code></pre>
  
  <p>I expected that it would yield:</p>
  
  <pre><code>Vector size: 3
  100
  101
  102
  Removed element: 100
  Destroy of id: 100
  Vector size: 2
  101
  102
  </code></pre>
  
  <p>But instead, I get this result:</p>
  
  <pre><code>Vector size: 3
  100
  101
  102
  Removed element: 100
  Destroy of id: 100
  Vector size: 3
  Segmentation fault: 11
  </code></pre>
  
  <p>Why is my vector size still 3, and why am I getting a segmentation fault? How can I get my desired result?</p>