types_is_within_lifetime

types_is_within_lifetime (객체 수명 내 존재 여부 확인)

std::is_within_lifetime는 포인터가 가리키는 객체가 현재 수명(lifetime) 내에 있는지 확인하는 C++26 유틸리티예요. 이 함수는 상수 표현식 평가 중에 유니온(union)의 활성 멤버를 검사할 때 특히 유용해요. 컴파일 타임에 객체의 수명 상태를 안전하게 판별할 수 있도록 도와줘요.

출처: cppreference

본문

정의

<type_traits> 헤더에 정의되어 있어요.

template < class T > consteval bool is_within_lifetime ( const T * ptr ) noexcept ;

설명

포인터 ptr이 수명 내에 있는 객체를 가리키는지 결정해요.

핵심 상수 표현식(core constant expression) E를 평가하는 동안, std::is_within_lifetime 호출은 ptr이 다음 조건 중 하나를 만족하는 객체를 가리키지 않으면 ill-formed예요:

  • 상수 표현식에서 사용 가능한 객체, 또는
  • 그 완전한 객체의 수명이 E 내에서 시작된 객체

매개변수

ptr - 검사할 포인터

반환값

포인터 ptr이 수명 내에 있는 객체를 가리키면 true, 그렇지 않으면 false를 반환해요.

참고 사항

Feature-test macro 표준 기능
__cpp_lib_is_within_lifetime 202306L (C++26) 유니온 대안이 활성 상태인지 확인하는 std::is_within_lifetime
202603L (C++26) std::is_within_lifetime 확장

예제

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);
}

관련 항목

is_implicit_lifetime (C++23) 타입이 암시적 수명 타입인지 확인해요 (클래스 템플릿)

더 알아보기 (Learn more)

cppreference