Namespaces
Variants

contract_assert statement (since C++26)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

contract_assert 文は、関数またはラムダ本体に現れる契約表明であり、内部条件を検証するために使用されます。これは実行中に条件が成立することを保証し、条件が false と評価されるか、評価が例外によって終了した場合にデバッグビルドでは違反(例:終了)を引き起こし、パフォーマンス向上のためリリースビルドでは無視される可能性があります。

目次

翻訳のポイント: - 「Contents」を「目次」に翻訳 - HTMLタグ、属性、クラス名は一切変更せず保持 - ` `内のテキストはC++関連の用語(Syntax, Keywords, Exampleなど)のため翻訳せず保持 - 数字、リンク、構造は完全に維持 - フォーマットとインデントを元のまま保持

構文

contract_assert attr  (オプション) ( predicate ) ;
attr - 任意の数の 属性
predicate - true と評価されるべきブーリアン式

キーワード

contract_assert

注記

機能テストマクロ 標準 機能
__cpp_contracts 202502L (C++26) Contracts

contract_assert は、ベクトルのノルムが正であり、かつ normal または subnormal のいずれかであることを保証します。

template <std::floating_point T>
constexpr auto normalize(std::array<T, 3> vector) noexcept
    pre(/* is_normalizable(vector) */)
    post(/* vector: is_normalized(vector) */)
{
    auto& [x, y, z]{vector};
    const auto norm{std::hypot(x, y, z)};
    // 正規化の安全性のためのデバッグチェック
    contract_assert(std::isfinite(norm) && norm > T(0));
    x /= norm, y /= norm, z /= norm;
    return vector;
}

サポート状況

C++26 機能

提案文書

GCC
Clang
MSVC
Apple Clang
EDG eccp
Intel C++
Nvidia HPC C++ (ex PGI)*
Nvidia nvcc
Cray


コントラクト ( FTM ) * P2900R14

参考文献

  • C++26標準 (ISO/IEC 14882:2026):
  • 8.(7+ c  ) アサーション文 [stmt.contract.assert]

関連項目

ユーザー指定の条件が true でない場合、プログラムを異常終了させる。 リリースビルドでは無効化される場合がある。
(関数マクロ)
契約表明 (C++26) 実行中の特定の時点で成立していなければならないプロパティを指定する
static_assert 宣言 (C++11) コンパイル時の表明チェックを実行する
関数契約指定子 (C++26) 事前条件 ( pre ) と事後条件 ( post ) を指定する
[[ assume ( )]]
(C++23)
指定された時点で が常に true と評価されることを指定する
(属性指定子)