title: C++ return value optimization
body: <p>This code:</p>
  
  <pre><code>#include &lt;vector&gt;
  
  std::vector&lt;float&gt; getstdvec() {
      std::vector&lt;float&gt; v(4);
  
      v[0] = 1;
      v[1] = 2;
      v[2] = 3;
      v[3] = 4;
  
      return v;
  }
  
  int main() {
      std::vector&lt;float&gt; v(4);
  
      for (int i = 0; i != 1000; ++i)
      {
          v = getstdvec();
      }
  }
  </code></pre>
  
  <p>My incorrect understanding here is that the function getstdvec shouldn't have to actually allocate the vector that it's returning. When I run this in valgrind/callgrind, I see there are 1001 calls to malloc; 1 for the initial vector declaration in main, and 1000 for every loop iteration.</p>
  
  <p>What gives? How can I return a vector (or any other object) from a function like this without having to allocate it every time?</p>
  
  <p>edit: I'm aware I can just pass the vector by reference. I was under the impression that it was possible (and even preferable) to write a function like this that returns an object without incurring an unnecessary allocation.</p>