C++26: Std:Is_within_lifetime
Source: Hacker News
What does std::is_within_lifetime do?
C++26 adds
bool std::is_within_lifetime(const T* p);
to the “ header. The function checks, during constant evaluation, whether p points to an object that is currently within its lifetime.
The most common use case is checking which member of a union is active:
union Storage {
int i;
double d;
};
constexpr bool check_active_member() {
Storage s;
s.i = 42; // `i` becomes the active member
return std::is_within_lifetime(&s.i); // true
// std::is_within_lifetime(&s.d) would be false here
}
Properties and the name
It’s consteval only
std::is_within_lifetime is consteval, so it can be used only during compile‑time evaluation. At runtime you would typically track the active member with additional state; the compiler does not retain the same lifetime‑tracking information outside constant evaluation.
Why a pointer instead of a reference?
The function takes a pointer rather than a reference to avoid complications with temporary objects and lifetime‑extension rules. A pointer makes it explicit that you are querying a specific memory location.
Why not “is_union_member_active”?
The committee chose a more general name because the mechanism can be useful beyond unions. It provides a generic way to query object lifetime in constant evaluation, which may have future applications.
The original motivation
The proposal was driven by a concrete problem: implementing an Optional with minimal storage overhead. Consider a type that stores either a bool value or nothing, using a union to save space:
struct OptBool {
union { bool b; char c; };
constexpr auto has_value() const -> bool {
// How to know if `b` is the active member?
// Reading `b` when `c` is active is undefined behavior.
}
};
At runtime you could use a sentinel value in c (e.g., 2) to indicate “no value”. During constant evaluation, however, you need a way to detect the active member without such tricks. std::is_within_lifetime solves this:
struct OptBool {
union { bool b; char c; };
constexpr auto has_value() const -> bool {
if consteval {
return std::is_within_lifetime(&b);
} else {
return c != 2; // sentinel value for runtime
}
}
constexpr bool value() const {
return b;
}
};
In constexpr contexts the function tells us whether b is currently alive; at runtime we fall back to the sentinel check.
Compiler support
As of February 2026, no major compiler has implemented std::is_within_lifetime yet. Support will arrive as the feature matures in C++26 implementations.
Conclusion
C++26’s std::is_within_lifetime provides a focused, constexpr‑only tool for querying object lifetime, primarily useful for determining the active member of a union without invoking undefined behavior. Its design—pointer argument, consteval restriction, and generic name—reflects a careful balance between current needs and future extensibility, making constexpr evaluation more practical and expressive.