title: Binding temporaries to references
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object">How come a non-const reference cannot bind to a temporary object?</a>  </p>
  </blockquote>
  
  
  
  <p>First up, I understand that the standard mandates that temporaries can only be bound to const references, and, as I understand it, in this case the lifetime of the temporary is bound to the lifetime of the reference.</p>
  
  <p>Other than "because the standard says so..." why is it such a good idea to prevent temporaries being bound to general (i.e. non-const) references??</p>
  
  <p>Consider the following, where we have a routine that requires some workspace:</p>
  
  <pre><code>void foo(std::vector&lt;mytype&gt; &amp;data, std::vector&lt;mytype&gt; &amp;work)
  { // we do something to DATA but we need to use the workspace WORK
    // we may resize WORK, write to it, generally use it in a non-const way
  
    // we want to pass WORK as a parameter because we want to have the option
    // of pre-allocating it (for efficiency, FOO may, but is not always, called
    // inside a loop)
  }
  </code></pre>
  
  <p>Why would it be so evil to make an isolated call to <code>foo</code> as follows:</p>
  
  <pre><code>// case 1
  // DATA already created elsewhere
  foo(data, std::vector&lt;mytype&gt;() );
  </code></pre>
  
  <p>Of course we could do something like this:</p>
  
  <pre><code>// case 2
  // DATA already created elsewhere
  std::vector&lt;mytype&gt; work;
  foo(data, work);
  </code></pre>
  
  <p>But then the lifetime of <code>work</code> is extended until the end of the enclosing block, which can be unwanted.</p>
  
  <p>I know that there are ways to work around this kind of thing, but case 1 here would be a neat way of doing things, except we're not allowed.</p>