名稱空間
變體
操作

std::is_within_lifetime

來自 cppreference.com
< cpp‎ | 型別
 
 
 
定義於標頭檔案 <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 指向的物件

目錄

[編輯此節:引數] 引數

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