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 가 자신의 lifetime 범위 내에 있는 객체를 가리키는지 여부를 결정합니다.

표현식 E 를 핵심 상수 표현식으로 평가하는 동안, std::is_within_lifetime 에 대한 호출은 ptr 가 객체를 가리키지 않는 한 형식이 잘못되었습니다.

  • 상수 표현식에서 사용 가능한 것이거나,
  • 완전한 객체의 수명이 E 내에서 시작된 경우.

목차

매개변수

p - 탐지할 포인터

반환값

true 만약 포인터 ptr 가 수명 주기 내에 있는 객체를 가리키는 경우; 그렇지 않으면 false .

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_is_within_lifetime 202306L (C++26) union 대안이 활성 상태인지 확인

예제

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