I think it's important to note that you the expected behavior is undefined here, and that what is happening with your compiler and optimization settings cannot be counted on, and are dangerous. You can rationalize what your compiler happens to be doing today, but that could change tomorrow when your compiler is patched, when you link in different code, or when your OS is patched. (Those things may not actually affect this particular behavior, but in general, those things could certainly affect other "undefined behavior".
If you ignore the fact that the if (true)
might or might not be optimized out (and might change things), b
goes out of scope.. but the compiler could treat that any number of ways. The compiler might put it on the stack, and leave it there, making it possible but not guaranteed to reference it "uncorrupted" for a while. Even when c
gets instantiated, the compiler might or might not allocate new space on the stack. In this case, if you print out the addresses of b
and c
, you might even be able to tell that they are adjacent memory spaces in the stack area. But the most important thing to remember is that you should assume that the compiler is allowed to do anything it wants with b
(including do nothing) now that it's out of scope.
All that said, I don't understand your question about "what is the proper way"... what are you really trying to ask?