std::is_within_lifetime
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > consteval bool is_within_lifetime( const T* ptr ) noexcept; |
(自 C++26 起) | |
确定指针 ptr 是否指向在其生命周期内的对象。
在核心常量表达式中求值表达式 E 期间,除非 ptr 指向一个对象,否则对 std::is_within_lifetime
的调用是病态的
- 该对象在常量表达式中可用,或者
- 其完整对象的生命周期在 E 内开始。
目录 |
[编辑] 参数
p | - | 要检测的指针 |
[编辑] 返回值
true 如果指针 ptr 指向在其生命周期内的对象;否则 false。
[编辑] 说明
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_is_within_lifetime |
202306L |
(C++26) | 检查联合体的备选项是否处于活动状态 |
[编辑] 示例
std::is_within_lifetime
可用于检查联合体的成员是否处于活动状态
运行此代码
#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); }