https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110394
--- Comment #7 from Andrew Pinski <pinskia at gcc dot gnu.org> --- (In reply to jackyguo18 from comment #6) > @Andrew Pinski - Thanks, just confirmed that that was the issue. > > Why doesn't GCC choose to delete the function (thus causing the weird > behaviour) early at lower optimization levels? > > Seems kinda strange it would work at -O2. Most likely inlining more and being more agressive of doing some optimizations. Since it is undefined behavior if you use the object after the lifetime ends, it is just happened to work at different levels of optimization really.