title: Dangling reference solution
body: <p><code>T&amp;&amp; operator[](std::size_t n) &amp;&amp; noexcept {std::cout&lt;&lt;&quot;move&quot;&lt;&lt;std::endl; return std::move(vec[n]); }</code><br />
  I cannot get the expected result in this part.
  I predict a dangling reference happens.</p>
  <p><code>T operator[](std::size_t n) &amp;&amp; noexcept {std::cout&lt;&lt;&quot;move&quot;&lt;&lt;std::endl; return std::move(vec[n]); }</code><br />
  This works well.
  Why doesn't T&amp;&amp; increase lifetime?</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdlib.h&gt;
  #include&lt;vector&gt;
  
  template&lt;typename T, typename Alloc = std::allocator&lt;T&gt;&gt;
  class my_vector
  {
    std::vector&lt;T, Alloc&gt; vec;
  
  public:
    my_vector(std::initializer_list&lt;T&gt; init) : vec{init} {}
  
    T&amp;&amp; operator[](std::size_t n)  &amp;&amp; noexcept {std::cout&lt;&lt;&quot;move&quot;&lt;&lt;std::endl; return std::move(vec[n]); } // moveしたものを参照するとごみを参照してることになる
      //T operator[](std::size_t n)  &amp;&amp; noexcept {std::cout&lt;&lt;&quot;move&quot;&lt;&lt;std::endl; return std::move(vec[n]); } 
  };
  
  int main()
  {
  
      auto&amp;&amp; vec = my_vector&lt;int&gt;{1, 2, 3}[0]; //case3 move
      std::cout&lt;&lt;vec&lt;&lt;std::endl; //0
  
  }
  
  </code></pre>