HeadlinesBriefing HeadlinesBriefing.com

C++26 Contracts: Preconditions and Postconditions

Hacker News •
×

The Standard Library hardening article discussed invalid container access and other broken preconditions, described in terms of "contracts." This post examines contracts in C++26 and applies them to user code.

The starting point is a simple function, get_value, which returns an element of a std::vector at a given index. Using assert, the requirement that the index be valid is placed inside the implementation. Anyone reading only the declaration sees a vector and an index, without the relationship between them. Assertions are also disabled entirely when NDEBUG is defined.

C++26 contracts move the requirement into the function itself using the pre(...) syntax after the parameter list. A precondition expresses a condition expected to hold on entry, and it can be placed on the declaration so the requirement is visible to anyone reading the API. This feature was introduced through P2900, Contracts for C++.

Contracts differ from assert in several ways. Requirements can live in declarations, making them visible without reading the implementation. Evaluation semantics offer more flexibility than the all-or-nothing NDEBUG switch, including ignoring a check, reporting a violation and continuing, or terminating the program, with availability determined by the compiler. Contracts also separate what the caller must provide (preconditions) from what the function promises to return (postconditions), so checks no longer need to be repeated manually before each return statement. Contracts remain useful for documenting APIs even when runtime checking is disabled.

Source: Hacker News · Summarized by HeadlinesBriefing