C++26: std::is_within_lifetime
14 points by raymii
14 points by raymii
The OptBool example is not convincing. Isn’t the read of the char member UB if the active one is the bool? If that read was not UB then you could have done it at compile-time as well.
Seems like the example is taken directly from cppreference but I’m not convinced either
The original paper describing the feature explains the issue: we are allowed to read from the char at runtime because of the special exception of chars in this context. But not during constant evaluation.
As a (mostly) outsider, I can't help but see the need for this and previously added things like std::launder, std::construct_at, std::start_lifetime_as etc. as results of the bizarre decision to have types (semantically) exist in memory. Even at runtime, you can run into really surprising UB with this, but the fact that there are additional, stricter rules for consteval is just baffling.
On the other hand, as far as I understand, the fact that types/objects exist in memory is what enables type-based alias analysis, which probably wins you 5% or so on benchmarks. So perhaps they have painted themselves into a corner.
Maybe I'm not seeing the bigger picture, but to me the motivation in the linked paper seems weak. I would implement that by only using two bits of a uint8_t.
Not sure why I would choose any of the other two ways, or why this feature would be useful for other things in the future. The wording in the paper for why the name was chosen is not very inspiring either: "This is probably useful, specifiable, and implementable."
I might be wrong here but if we want the implementation to conform to the existing std::optional API, the union might be the cleanest way to provide a type-safe reference to the underlying bool with no casting tricks.
Would your solution work in 99.999…% of cases? Yes, but then we’d have to tolerate a hack inside the STL where std::optional<bool> would have no underlying bool.