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 로 평가되거나 예외를 통해 평가가 종료되는 경우 디버그 빌드에서 위반(예: 종료)을 트리거하고, 성능을 위해 릴리스 빌드에서는 무시될 수 있습니다.

목차

구문

contract_assert attr  (선택적) ( predicate ) ;
attr - 임의의 개수의 attributes
predicate - true 로 평가되어야 하는 부울 표현식

키워드

contract_assert

참고 사항

기능 테스트 매크로 표준 기능
__cpp_contracts 202502L (C++26) Contracts

예제

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


계약 조건 ( 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 로 평가됨을 지정합니다
(속성 지정자)