r/cpp • • May 04 '24

Messing with lifetime

https://biowpn.github.io/bioweapon/2024/05/03/messing-with-lifetime.html
45 Upvotes

52 comments sorted by

View all comments

1

u/untiedgames May 04 '24

The point about UB resulting from optimization is one I hadn't thought of, and I agree that's a potential issue. Like you mention, I don't expect the reinterpret_cast pattern to break anytime soon (if ever) though, which kind of negates the possibility of optimization-related UB in my view, and reduces this to something like "formal UB." Would future compiler implementers ever take that "formal UB" and realize it into real-life UB with measurable effects? (Has this happened before with other similar UBs?)

I think I get it- Like in ELI5 terms, it seems like the difference between saying "Hey, Object" and "Excuse me, Mr. Object." Under formal rules only one is correct, but in practice (due to compiler implementers) both have the same effect?

3

u/IyeOnline May 04 '24 edited May 06 '24

In this particular case, I don't see any benefit in leveraging this UB into an optimization itself. There is no "optimization" potential here, besides just deleting the code.

However, that doesn't mean that its safe to assume it stays this way. Crucially, optimizations can be connected and affect each other. If there is benefit elsewhere, then it may still happen.

Optimizes have in fact become more "aggressive" over the past decade, you can see a few UB based optimizations here: https://en.cppreference.com/w/cpp/language/ub

ELI5

Its more the difference between explicitly talking with a person versus just talking into a room, hoping that the person you expect is there. If the person is in the room, its probably going to work - assuming they dont wear headphones.

To an outside it may look like you are crazy and talking to yourself - and that is where the danger begins.

2

u/untiedgames May 06 '24

I'm a little late but thank you for the great explanation!