To my surprise, gcc 11.2 accepts this code, but only in C++20 mode:
struct Base {};
struct Derived : Base { int i; };
int f(Base& b) { return static_cast<Derived>(b).i; }
// ^~~~~~~ oops, forgot the `&`
Likewise, MSVC 19.29 accepts it in C++20 mode and rejects it in C++17 mode, but clang rejects it even in C++20 mode.
Looking at the assembler output, f
always returns 0
, so it's ignoring the actual data of any potential Derived
passed to f
.
Is this UB, or is it legal in C++20, and if so, why?