hn.today

C++26 Contracts: Introduction to Preconditions and Postconditions

cppstories.com111 points107 comments
Screenshot of C++26 Contracts: Introduction to Preconditions and Postconditions

C++26 adds language-level contracts with three constructs: pre(...) for caller obligations, post(...) for guarantees on normal return, and contract_assert(...) for checks inside a function. Contracts are attached to a function by its first declaration (typically in headers), so later declarations may omit but cannot change them; contracts do not affect function types or overload resolution. The standard defines four runtime evaluation semantics - ignore, observe, enforce, and quick-enforce - which determine whether predicates are skipped, reported, or cause termination. There is no portable syntax to force a particular policy per assertion; the implementation chooses the active semantic, so code must not depend on contract checks for required control flow.

GCC 16 implements C++26 contracts and exposes flags (-fcontracts and -fcontract-evaluation-semantic=...) and a replaceable violation handler receiving std::contracts::contract_violation. Predicates are subject to constification rules (value parameters used in postconditions must be const and mutation inside predicates is rejected), and predicated side effects are discouraged because checks can be omitted. Contracts are explicitly not a substitute for input validation or error-handling; use normal control flow for expected runtime errors. Expensive predicates can hurt performance, so measure representative workloads and keep contracts lean and declarative.

Read on cppstories.com107 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.