When I was looking for the next topic for my posts, my eyes stopped on std::is_within_lifetime . Dealing with lifetime issues is a quite common source of bugs, after all. Then I clicked on the link and I read Checking if a union alternative is active. I scratched my head. Is the link correct?
It is — and it totally makes sense.
Let’s get into the details and first check what P2641R4 is about.
What does std::is_within_lifetime do?
C++26 adds bool std::is_within_lifetime(const T* p) to the
The most common use case is checking which member of a union is currently active. Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 union Storage { int i ; double d ; }; constexpr bool check_active_member () { Storage s ; s . i = 42 ; // At this point, 'i' is the active member return std :: is_within_lifetime ( & s . i ); // returns true }
In this example, after assigning to s.i , that member becomes active. The function std::is_within_lifetime(&s.i) returns true , confirming that i is within its lifetime. If we checked std::is_within_lifetime(&s.d) at this point, it would return false since d is not the active member.
Properties and the name
The function has some interesting design choices that are worth discussing.
... continue reading