Undefined behavior can appear with or without templates. But other than that, yes, it is viscerally shocking to see on Compiler Explorer that your entire function has been compiled to a single instruction, ud2.
Seeing an entire function compiled down to a single ud2 instruction in Compiler Explorer was the moment I truly grasped the power of undefined behavior.
Templates are just tools — but undefined behavior (UB) is the real shadow lord. That seemingly innocent line of C++ code you wrote? The compiler might decide it has no meaning at all and emit ud2 — a deliberate “invalid operation” that crashes the program.
This isn’t just a language “gotcha”; it’s the compiler shouting:
“Your code makes no sense to me — so I’m terminating it with prejudice.”
It’s both technically fascinating and philosophically unsettling.
Who should bear the burden of balancing performance and safety?
Should we be more careful developers, or should the language take more responsibility?
Or… is this precisely the case for Rust?
The compiler didn’t betray you. It simply honored your undefined contract.