title: Lifetime of C++ temporary extended to lexical when assigned to const&
body: <p>I was suprised recently to find a temporary variable in C++ being promoted to having full lexical scope:</p>
  
  <pre><code>class Foo {
  public:
      Foo() {
          std::cout &lt;&lt; "A";
      }
      ~Foo() {
          std::cout &lt;&lt; "B";
      }
  };
  
  int main(void)
  {
      // Prints "ACB", showing the temporary being promoted to having lexical scope.
      const Foo&amp; f = Foo();
      std::cout &lt;&lt; "C";
      return 0;
  }
  </code></pre>
  
  <p>Aside from the dubious behavior of assigning a temporary to a reference, this actually works just fine (tested in VS2010 and G++ v4.1).  The output is <code>ACB</code>, showing clearly that the temporary object has been promoted to having lexical scope, and is only destructed at the end of the function (<code>B</code> is printed after <code>C</code>).</p>
  
  <hr>
  
  <p>Other temporary variables don't behave this way:</p>
  
  <pre><code>int main(void)
  {
      // Prints "ACBD", showing that the temporary is destroyed before the next sequence point.
      const int f = ((Foo(), std::cout &lt;&lt; "C"), 5);
      std::cout &lt;&lt; "D";
      return 0;
  }
  </code></pre>
  
  <p>As per my code comment this prints <code>ACBD</code>, showing that the temporary variable is kept until the entire expression has finished evaluating (why <code>C</code> is printed before <code>B</code>), but still destroyed before the next sequence point (why <code>B</code> is printed before <code>D</code>).  (This behaviour was how I thought all temporary variables in C++ worked.  I was very surprised at the earlier behaviour.)</p>
  
  <p><strong>Can someone explain when it is legal for a temporary to be promoted to have lexical scope like this?</strong></p>