Contracts in C++26
Contracts allow you to specify preconditions, postconditions, and invariants for functions.
Contracts should already be part of C++20 but were removed in the standard meeting in Cologne. Here is what Herb Sutter said about contracts on Sutter’s Mill: “contracts is the most impactful feature of C++20 so far, and arguably the most impactful feature we have added to C++ since C++11.”. With C++26, we probably get them.
This post is based on the proposal P2961R2.
First of all.
What is a Contract?
A contract specifies interfaces for software components in a precise and checkable way. These software components are functions and methods that must fulfill preconditions, postconditions, and invariants. Here are the definitions:
- A precondition: a predicate that is supposed to hold upon entry in a function.
- A postcondition: a predicate that is supposed to hold upon exit from the function.
- An assertion: a predicate that is supposed to hold at its point in the computation.
The precondition and the postcondition are placed outside the function definition, but the invariant is placed inside the function definition. A predicate is an expression that returns a boolean.
Before I show you the first example, let me write about the contract design goals.
Design Goals
- The syntax should fit naturally into existing C++. The intent should be intuitively understandable by users unfamiliar with contract checks without creating any confusion.
- A contract check should not resemble an attribute, a lambda, or any other pre-existing C++ construct. It should sit in its own, instantly recognisable design space.
- The syntax should feel elegant and lightweight. It should not use more tokens and character than necessary.
- To aid readability, the syntax should visually separate the different syntactic parts of a contract check. It should be possible to distinguish at a glance the contract kind, the predicate, the name for the return value … (Proposal P2961R2)
Now comes the first example.
First example
int f(int i) pre (i >= 0) post (r: r > 0) { contract_assert (i >= 0); return i+1; }
pre
and post
- adds a precondition (postcondition). A function can have an arbitrary number of preconditions.(postconditions). They can be intermingled arbitrarily.
- are a contextual keyword. A contextual keyword is a keyword in specific contexts but an identifier outside that context.
- are positioned at the end of the function declaration.
post
- can have a return value. An identifier must be placed before the predicate, followed by a colon.
contract_assert
- is a keyword. Otherwise, it could not be distinguished from a function call.
You may wonder why the assertion has such a long keyword.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
The assert
Issue
The ideal keyword for the assertion would be assert
but not contract_assert
. assert
is used in most programming languages to express contract-like assertions. But C++ has a legacy issue.
#include <cassert> void f() { int i = get_i(); assert(i >= 0); // identical syntax for contract assert and macro assert! use_i(i); }
assert
is already a macro from the header <cassert>
.
Break Of Contract
The break of the contract causes a runtime error.
// contract.cpp #include <iostream> int f(int i) pre (i >= 0) post (r: r > 0) { contract_assert (i >= 0); return i+1; } int main() { std::cout << '\n'; f(-1); std::cout << '\n'; }
What’s Next
My next post will continue with the more minor C++26 core language features.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
My special thanks to Embarcadero | |
My special thanks to PVS-Studio | |
My special thanks to Tipi.build | |
My special thanks to Take Up Code | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,