title: What happens in the stack when a const reference is bound to a temporary?
body: <p>The C++ standard allows to bind const references to rvalues, therefore extending the lifetime of the temporary until the reference goes out of scope. However, I cannot figure out how this is actually compiled, let me explain with an example:</p>
  
  <pre><code>std::string foo() {
      return std::string("foo");
  }
  
  void bar() {
      VeryBigObject obj;
      // Perhaps do something with the big object
  }
  
  int main(int, char **) {
      const std::string &amp;foo_str = foo();
      bar();
      return 0;
  }
  </code></pre>
  
  <p>As far as I know, using an x86 architecture as an example, what happens there is that first the function <code>foo()</code> is called and the string object is constructed in the stack, which means that the needed amount of space is subtracted from the <code>rsp</code> register (assuming 64 bit architecture); afterwards, the <code>rsp</code> register is returned to its original value, freeing the stack space that the function <code>foo()</code> was filling, and, if I understand correctly, the call to <code>bar()</code> would use that stack space to construct the <code>VeryBigObject</code>, which would overwrite the string.</p>
  
  <p>With all this in mind, how can the lifetime of the string be prolonged after the call to <code>foo()</code> in the assembly domain?</p>