The variable is actually never used.
- The method call is inlined1, so the variable is not passed as an argument.
- The method itself doesn't use
this in any way, so the variable is not used at all.
Above is independent of turning optimizations on or off.
As a matter of fact, in optimized code the variable will never exist at all - not even as memory allocation.
Question about a similar case: Extern variable only in header unexpectedly working, why?
.
1 All methods defined in the class body are inlined by default.
Is it an Undefined Behavior?
Yes it is. Calling the method requires this to point at an actual, initialized intance of object to be well-formed. As Nir Friedman points out, compiler is free to assume that and optimize on that base (and IIRC this kind of optimizations can happen even with -O0!).
I'd personally expect the specific code in question to work in any practical conditions (as the pointer value is really irrelevant), but I would never rely on that. You should fix your code right now.
Detection
To detect usage of uninitialized variables in Clang/GCC, use option -Wuninitialized (or simply use -Wall, which includes this flag).
-Wuninitialized should mostly cover use of stack-allocated memory, though I guess some use of stack-allocated arrays may still slip. Some compilers may support including extra runtime checks for uninitialized reads with -fsanitize=... options, like -fsanitize=memory in Clang (thx, chtz). These checks should cover the edge cases as well as the use of heap-allocated memory.
print()isn't virtual, so the entire call can be bound at compile time.print.Printer::print()doesn't modify the object, so it doesn't actually need a validthispointer. And since dereferencing a uninitialized pointer is UB the compiler can do whatever it wants, so it probably just inlinedprint()straight intomain()- take a look at the disassembly if you want to know what happened.