title: Is it UB to keep a const-reference to a local variable?
body: <p>I'm running into multiple problems when compiling my code optimizations enabled (MSVC to be precise). The actual case is part of a large codebase and requires a complex setup to replicate, but essentially it boils down to the following construct:</p>
  <pre><code>struct VariableView
  {
      const void* pValue;
  };
  
  template&lt;typename Type&gt;
  [[nodiscard]] VariableView createView(const Type&amp; value)
  {
      return {&amp;value};
  }
  
  void serializeStruct(Struct value)
  {
      const auto view = createView(value);
  
      serializeGeneric(view);
  }
  </code></pre>
  <p>The bug I'm experiencing revolves around the content of &quot;value&quot; becoming overwritten after &quot;createView&quot; is called but before/right at the point that &quot;serializeGeneric&quot; is called. This is as far as I've been able to tell via debugging and looking at the generated assembly, so what I'm assuming is that the compiler somehow (wrongly) assumes that the variable &quot;value&quot; is no longer used after createView is called, and thus decides to reassign the next required values to its original local.</p>
  <p>However, before I file a bug-report to the MSVC-compiler, I'd like to make sure: Is what I'm doing here actually supposed to be valid C++ due to the standard, or am I running into UB by storing the address of the local variable in the &quot;VariableView&quot;-struct the way I'm doing it?</p>
  <p>EDIT: Ok, so I've been able to boil down the problem. The compilers confusion seems to be coming from the fact that the type in the actual code is deduced by a template. This is the full code to reproduce the problem:</p>
  <p><a href="https://www.paste.org/120337" rel="nofollow noreferrer">https://www.paste.org/120337</a>
  (Sorry, the editor keeps saying my code is not properly formatted so I had to use an external site).</p>
  <p>In MSVC with /O2, the first two variables of the &quot;Temporary&quot; struct in accessData will be corrupted (O1 or below solves the issue. Passing the string_view by value seems to be what causes the values to be overwritten.
  The bug actually also disappears if I replace the type-traits in the argument-list their plain definition, even though the trait resolves to the very same underlying type. So, please let me know if you think there is something else fishy here that I'm missing, but I'll be filing a bug-report as well since I'm now very sure that its not right (and also I now have a minimal example).</p>
  <p>EDIT2: My report has been filed (<a href="https://developercommunity.visualstudio.com/t/Type-trait-as-argument-type-leads-to-opt/1572875" rel="nofollow noreferrer">https://developercommunity.visualstudio.com/t/Type-trait-as-argument-type-leads-to-opt/1572875</a>) and is already under investigation.</p>