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 语句是一种合约断言,可出现在函数或lambda函数体中以验证内部条件。它确保该条件在执行期间成立,在调试版本中若条件评估为 false 或评估过程因异常退出则会触发违规(例如终止程序),在发布版本中为性能考虑可忽略该断言。

目录

语法

contract_assert 属性  (可选) ( 谓词 ) ;
attr - 任意数量的 属性
predicate - 应求值为 true 的布尔表达式

关键词

contract_assert

注释

功能测试宏 标准 功能特性
__cpp_contracts 202502L (C++26) 契约

示例

contract_assert 确保向量的范数为正且为 正规数或次正规数

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


Contracts ( 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 ( expression )]]
(C++23)
指定在给定点 表达式 始终求值为 true
(属性说明符)