skip to content

How do C++26 contracts — pre, post and contract_assert — work, and what do the ignore, observe, enforce and quick-enforce semantics do?

level: seniorimportance: should knowfreq 25%

answer

  1. on the declaration, visible to callers
  2. four semantics, implementation-chosen
  3. handler then continue or terminate
  4. ::handle_contract_violation
  5. not on virtual functions

basics

~20 s

pre and post attach preconditions and postconditions to a function declaration, and contract_assert checks inside a body. Each evaluation uses an implementation-chosen semantic: ignore skips it, observe calls the violation handler and continues, enforce calls it then terminates, quick-enforce terminates at once.

solid answer

~40 s

A C++26 **contract assertion** has a `bool` predicate. **`pre(expr)`** and **`post(r: expr)`** sit on a function declaration, so callers and tools see them; **`contract_assert(expr);`** is a statement inside a body. Which **evaluation semantic** applies is implementation-defined — typically a build option — and may differ between evaluations: **ignore** does not check; **observe** checks and, on violation, calls the **contract-violation handler** and then continues; **enforce** calls the handler and then terminates; **quick-enforce** terminates immediately without the handler. The standard recommends enforce by default and an option for all-ignore and all-enforce. The handler is `::handle_contract_violation(const std::contracts::contract_violation&)`; whether a program may replace it is implementation-defined. Predicates see outside variables as `const`, and virtual, deleted and first-declaration-defaulted functions cannot carry `pre` or `post`.

go deeper

for a junior

Know the three spellings — pre, post and contract_assert — and that a failed contract can stop the program instead of continuing with bad data.

for a middle

Explain the four evaluation semantics and the violation handler, and how contracts differ from the assert macro and NDEBUG.

for a senior

Plan an introduction: observe first in production to find false assertions, then enforce; mind const predicates, unreliable side effects and the ban on virtual functions.

for a principal

Set the build policy: which semantic each configuration uses, whether the handler is replaced and what it reports, and how mixed semantics across libraries are kept safe.

## What contracts add Before C++26, preconditions lived in comments, in the `assert` macro, or in hand-rolled checking macros. **Contracts** make them part of the language. A **contract assertion** has a **predicate**, an expression of type `bool`, and comes in three forms: ```cpp // C++26 (N5050); not accepted by Apple clang 21, GCC 16 needs -fcontracts int checked_div(const int num, const int den) // post names them, so const pre(den != 0) // precondition, on the declaration post(r: r * den <= num) // postcondition; r names the result { contract_assert(num >= 0); // assertion statement inside the body return num / den; } ``` Because `pre` and `post` are part of the **declaration**, callers, static analysers and documentation tools can see them, which a macro inside the body never allowed. ## Evaluation semantics Every evaluation of a contract assertion uses one of four **evaluation semantics**. Which one is **implementation-defined**; compilers expose it as an option, and it may differ between evaluations of the same assertion, even between translation units. | Semantic | Checks the predicate? | On violation | |---|---|---| | ignore | no | nothing happens | | observe | yes | calls the violation handler, then continues after the assertion | | enforce | yes | calls the violation handler, then terminates the program | | quick-enforce | yes | terminates at once, without calling the handler | Observe, enforce and quick-enforce are the **checking** semantics; enforce and quick-enforce are the **terminating** ones. The standard recommends that implementations offer an option to translate the whole program with ignore and another with enforce, and that **enforce be the default**. A contract violation is a false predicate, a predicate that exits through an exception, or a predicate that is not a constant expression during constant evaluation. Termination means `std::terminate`, `std::abort` or ending execution, at the implementation's choice. ## The violation handler On observe or enforce, a violation calls the **contract-violation handler**, a function named `::handle_contract_violation` taking `const std::contracts::contract_violation&` from `<contracts>`. The implementation supplies a default that should print a diagnostic. Whether a program may **replace** the handler is implementation-defined; where it can, a replacement can log to the service's telemetry or throw an exception to unwind instead of terminating under enforce. ## Rules that surprise people - Inside a predicate, variables declared outside the assertion are treated as **`const`**, and `this` points to `const`, so a predicate cannot modify the state it checks through them. - A checked predicate may or may not actually be **evaluated**; the implementation may compute its value another way, so side effects in predicates are unreliable. - A postcondition that uses a **non-reference parameter** requires that parameter to be `const` on every declaration of the function, so the body cannot change the value the postcondition reads. - **Virtual functions**, deleted functions and functions defaulted on their first declaration cannot have `pre` or `post`. - Choosing different semantics in different translation units is allowed, which is what makes mixed-mode builds possible — and the standard notes it can cause ODR problems when a predicate's side effects feed a constant expression. ## Contracts versus assert | | `assert` macro | C++26 contracts | |---|---|---| | Mechanism | preprocessor, removed by `NDEBUG` | language construct | | Visible on the declaration | no | `pre` and `post` are | | Modes | on or off | ignore, observe, enforce, quick-enforce | | On failure | prints and calls `abort` | replaceable handler where supported, continue or terminate | The C++26 hardened standard library is built on the same machinery: a violated hardened precondition is a contract violation evaluated with a terminating semantic. ## Introducing contracts into an existing codebase A team adopting contracts usually proceeds in steps: 1. Convert the **preconditions already written as comments or `assert`s** at API boundaries into `pre` specifiers, where callers will see them. 2. Build and run with **observe** in a staging environment and route violations to logging, to find contracts that are wrong rather than callers that are. 3. Switch production builds to **enforce**, or to **quick-enforce** where code size or latency matters more than a diagnostic. 4. Keep predicates **cheap and free of side effects**, since they may be evaluated, skipped or evaluated differently per build. 5. Leave **virtual interfaces** to a non-virtual wrapper that carries the contract, because virtual functions cannot have one. ## Toolchain status GCC 16 implements contracts behind `-fcontracts`, describing support as experimental, and selects the semantic with `-fcontract-evaluation-semantic=` taking `ignore`, `observe`, `enforce` or `quick_enforce`, defaulting to enforce. The libc++ status page for LLVM 23 lists the contracts paper as not yet implemented, and Apple clang 21 rejects the `pre` syntax.

  • When would a team ship with the observe semantic?
    When it is introducing contracts into code that already runs in production and does not yet know which assertions fire. Observe reports violations through the handler without stopping the service, so the team can find wrong assumptions — in the code or in the contracts — before switching those assertions to enforce. Left on permanently, it turns checks into logging and lets execution continue past a broken precondition.
  • Why can't a C++26 virtual function carry pre or post?
    The final draft forbids it: a virtual function, a deleted function or a function defaulted on its first declaration shall not have function contract specifiers. Overriding raises questions — should a caller through the base see the base's contract or the override's? — that C++26 leaves for a later revision. A common workaround is a non-virtual public function with the contracts that calls a private virtual implementation.

The four semantics are like a building's smoke alarms in four modes: switched off, sounding while people keep working, sounding and then evacuating, or evacuating at once without the announcement.

  • Contracts are just the assert macro with new spelling.
  • Under observe, a violation terminates the program after logging.
  • Quick-enforce calls the violation handler before terminating.
  • The standard fixes one evaluation semantic for every implementation.
  • A predicate can update the variables it checks to fix the state.

Assumes the C++26 final draft N5050 (WG21 finished, ISO publication pending); C++23 is the latest published standard, so support varies by toolchain.