Namespaces
Variants

std:: is_within_lifetime

From cppreference.net
Utilities library
定义于头文件 <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 - 待检测的指针

返回值

若指针 ptr 指向的对象处于其生命周期内,则为 true ;否则为 false

注释

功能测试 标准 功能
__cpp_lib_is_within_lifetime 202306L (C++26) 检查联合体替代项是否处于活动状态

示例

std::is_within_lifetime 可用于检查联合体成员是否处于活跃状态:

#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);
{