名前空間
変種
操作

std::is_within_lifetime

From cppreference.com
< cpp‎ | types
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
is_within_lifetime
(C++26)
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
ヘッダ <type_traits> で定義
template< class T >
consteval bool is_within_lifetime( const T* ptr ) noexcept;
(C++26以降)

ポインタ ptr が、その生存期間内にあるオブジェクトを指しているかどうかを判定します。

コア定数式として式 E を評価している間、std::is_within_lifetime の呼び出しは、ptr がオブジェクトを指している場合を除き、不正形式 (ill-formed) となります。

  • それは、定数式で使用可能 なオブジェクトであるか、または
  • その完全なオブジェクトの生存期間が 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);
}
English 日本語 中文(简体) 中文(繁體)