std::is_within_lifetime(3)
okay so welcome to the std::is_within_lifetime(3) page from the C++ Standard Libary manual β yes bestie, we're doing consteval pointer stuff today π β¨
π¦ NAME π¦
std::is_within_lifetime β literally std::is_within_lifetime, that's the whole name, no cap.
β¨ Synopsis β¨
Defined in header <type_traits>
template< class T > (since C++26)
consteval bool is_within_lifetime( const T* ptr ) noexcept;
Determines whether the pointer ptr points to an object that is within its lifetime. π«Ά
During the evaluation of an expression E as a core constant expression, a call to std::is_within_lifetime is ill-formed unless ptr points to an object
- that is usable in constant expressions, or
- whose complete objectβs lifetime began within
E.
π Parameters π
pβ pointer to detect
(the page labels this one p here even though the signature says ptr β not me side-eyeing the docs π)
π Return value π
true if pointer ptr points to an object that is within its lifetime; otherwise false.
πΈ Example πΈ
std::is_within_lifetime can be used to check whether a union member is active:
// Run this code
#include <type_traits>
// an optional boolean type occupying only one byte,
// assuming sizeof(bool) == sizeof(char)
struct optional_bool
{
union { bool b; char c; };
// assuming the value representations for true and false
// are distinct from the value representation for 2
constexpr optional_bool() : c(2) {}
constexpr optional_bool(bool b) : b(b) {}
constexpr auto has_value() const -> bool
{
if consteval
{
return std::is_within_lifetime(&b); // during constant
evaluation,
// cannot read from c
}
else
{
return c != 2; // during runtime, must read from c
}
}
constexpr auto operator*() -> bool&
{
return b;
}
};
int main()
{
constexpr optional_bool disengaged;
constexpr optional_bool engaged(true);
static_assert(!disengaged.has_value());
static_assert(engaged.has_value());
static_assert(*engaged);
}
source/version: http://cppreference.com Β· date: 2024.06.10 Β· manual: std::is_within_lifetime(3) β mwah π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms