title: returning references to local variable
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2744264/returning-the-address-of-local-or-temporary-variable">Returning the address of local or temporary variable</a><br>
    <a href="https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope">Can a local variable’s memory be accessed outside its scope?</a>  </p>
  </blockquote>
  
  
  
  <p>Even knowing what happens as a result of the following snips it would be helpful to understand how it is happening. Four questions follow.</p>
  
  <p>Given:</p>
  
  <pre><code>int&amp; foo()
  {
      int i = 1;
      return i;
  }
  </code></pre>
  
  <p>And knowing that in the following a reference to the <strong>local named i</strong> is de-referenced into a temp that is assigned to intVal and <strong>local i</strong> disappears at the end of <em>foo()</em></p>
  
  <pre><code>int  intVal = foo();
  </code></pre>
  
  <p>First question - in the following, the right hand side of the expression is the same as above so is this a case where the compiler sees the left hand side and, based on context, knows not to de-reference the returned reference, and instead to create a new reference is initialized with it?</p>
  
  <p>Second question - and this alone makes the <strong>local i</strong> stick around while intRef is in scope?</p>
  
  <pre><code>int&amp; intRef = foo();
  </code></pre>
  
  <p>Third question - bellow <em>intPtr</em> gets address of <strong>local i</strong>. So, is the compiler using the context of the assignment and deciding to not de-reference to get a value before taking the address of the reference (rather than say taking the address of a temp containing the de-referenced value)?</p>
  
  <p>Fourth question - does <strong>local i</strong> stick around while <em>intPtr</em> is in scope?</p>
  
  <pre><code>int* intPtr = &amp;foo();   
  </code></pre>