title: C++: vector implementation and dynamic memory allocation
body: <p>I was looking to understand how <code>vector</code> is implemented in C++. There was a <a href="https://stackoverflow.com/questions/5159061/implementation-of-vector-in-c">previous question</a> that asked this, and so I took a look at it, and I have a small question. Assuming the implementation in the linked question is correct, let's look at this code:</p>
  
  <pre><code>int main(){
      Vector&lt;int&gt; test2 = test_Vector();
      cout &lt;&lt; test2[0] &lt;&lt; endl;
      return 0;
  }
  
  
  // below is NOT the STL vector object, but the one in the linked question,
  // in which the asker tries to implement STL vector himself/herself 
  Vector&lt;int&gt; test_Vector(){
      Vector&lt;int&gt; test;
      test.push_back(5);
      return test;
  }
  </code></pre>
  
  <p>As I understand it, the <code>test</code> <code>Vector</code> object is created locally, so when the <code>test_Vector</code> method returns, the local object goes out of scope, thereby calling the destructor and <code>delete</code>-ing the dynamic array. Since the code actually works and 5 is printed, I guess I'm wrong. What's the right explanation? </p>