title: Assign a value to an rvalue reference returned from function
body: <pre><code>#include &lt;utility&gt;
  template &lt;typename Container&gt;
  decltype(auto) index(Container &amp;&amp;arr, int n) {
      return std::forward&lt;Container&gt;(arr)[n];
  }
  </code></pre>
  
  <p>Make a function call :</p>
  
  <pre><code>#include &lt;vector&gt;
  index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
  </code></pre>
  
  <p>When function calling finished, the object <code>std::vector {1, 2, 3, 4, 5}</code> will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like</p>
  
  <pre><code>auto &amp;&amp;invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
  invisible_value = 9;
  </code></pre>
  
  <p>If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object <code>index(std::vector {1, 2, 3, 4, 5}, 2)</code> will be destroyed.</p>
  
  <p>This idea originated from 《Effective Modern C++》, Item3 : Understand <code>decltype</code>.</p>