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:
struct VariableView
{
const void* pValue;
};
template<typename Type>
[[nodiscard]] VariableView createView(const Type& value)
{
return {&value};
}
void serializeStruct(Struct value)
{
const auto view = createView(value);
serializeGeneric(view);
}
The bug I'm experiencing revolves around the content of "value" becoming overwritten after "createView" is called but before/right at the point that "serializeGeneric" 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 "value" is no longer used after createView is called, and thus decides to reassign the next required values to its original local.
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 "VariableView"-struct the way I'm doing it?
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:
https://www.paste.org/120337 (Sorry, the editor keeps saying my code is not properly formatted so I had to use an external site).
In MSVC with /O2, the first two variables of the "Temporary" 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).
EDIT2: My report has been filed (https://developercommunity.visualstudio.com/t/Type-trait-as-argument-type-leads-to-opt/1572875) and is already under investigation.