Destroying an int is a noop. The variable ceases to exist, but no runtime code need be run.
References or pointers to variables that cease to exist have undefined behaviour. Prior to initialization, newly created local variables have undefined state. So simply reusing an old variable for a new one is legal, the compiler doesn't have to prove there are no such outstanding references.
In this case, if it can prove that the value was constant 100
, it can even skip everything except the first initialization. And it can do this initialization "early" as there is no defined way to detect it happening early. In this case it is easy, and most compilers will do it easily; in more complex cases, less so. If you mark it const
, the compiler no longer has to prove it was unmodified, but rather can assume it!
Many of the areas that C++ leaves undefined exist in order to make certain optimizations easy.
Now, if you had something more complex, like a vector<int>{1,2,3,4,5}
, destruction and creation becomes less of a noop. It still becomes possible to 'hoist' the variable out of the loop, but much harder for the compiler. This is because dynamic allocation is a bit hard to optimize out sometimes.