std::is_within_lifetime
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > consteval bool is_within_lifetime( const T* ptr ) noexcept; |
(C++26 起) | |
确定指针 ptr 是否指向处于其 生存期内的对象。
在将表达式 E 作为核心常量表达式求值期间,对 std::is_within_lifetime
的调用是 ill-formed 的,除非 ptr 指向的对象
- 是 可在常量表达式中使用的,或
- 其完整对象的生存期始于 E 中。
目录 |
[编辑此节:参数] 参数
p | - | 要检测的指针 |
[编辑此节:返回值] 返回值
true 如果指针 ptr 指向处于其生存期内的对象;否则为 false。
[编辑此节:注解] 注解
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__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); }