title: Reference to element of vector returned by a function in C++
body: <p>Can someone verify that the following is a BUG, and explain why? I think I know, but am unclear about the details. (My actual problem involved a vector of enums, not ints, but I don't think it should matter.) Suppose I have the following code:</p>
  
  <pre><code>std::vector&lt;int&gt; f (void) {
    std::vector&lt;int&gt; v;
    v.push_back(5);
    return v;
  }
  
  void g (void) {
    const int &amp;myIntRef = f()[0];
    std::cout &lt;&lt; myIntRef &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>Am I correct that myIntRef is immediately a dangling reference, because the return value of f is saved nowhere on the stack?</p>
  
  <p>Also, is the following a valid fix, or is it still a bug?</p>
  
  <pre><code>  const int myIntCopy = f()[0];  // copy, not a reference
  </code></pre>
  
  <p>In other words, is the return result of f() thrown away before the 0th element can be copied?</p>