std::is_within_lifetime
来自cppreference.com
| 在标头 <type_traits> 定义
|
||
| |
(C++26 起) | |
判断指针 ptr 指向的对象是否在它的生存期内。
在对表达式 E 作为核心常量求值的过程中,对 std::is_within_lifetime 的调用非良构,除非 ptr 指向的对象满足以下任一条件:
- 该对象可用于常量表达式。
- 该对象的完整对象的生存期在
E之中开始。
参数
| ptr | - | 要检测的指针 |
返回值
在 ptr 指向的对象在它的生存期内的情况下返回 true;否则返回 false。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_is_within_lifetime |
202306L |
(C++26) | std::is_within_lifetime 检查某个联合体选项是否活跃
|
202603L |
(C++26) | 扩充 std::is_within_lifetime
|
示例
std::is_within_lifetime 可以用来检查联合体成员是否活跃:
Run this code
#include <type_traits>
// 一个只占据一个字节的可选布尔类型,假设 sizeof(bool) == sizeof(char)
struct optional_bool
{
union { bool b; char c; };
// 假设 true 和 false 的值表示都不与 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); // 在常量求值时不能从 c 读取
}
else
{
return c != 2; // 在运行时必须从 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);
}
参阅
(C++23) |
检查类型是否为隐式生存期类型 (类模板) |