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:
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
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
post
领英推荐
contract_assert
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.
Senior Staff Engineer/Manager at Qualcomm
1 周I think the runtime statement could be slightly better. In this case it should say something to the effect of "violated precondition check on line 6".
Desenvolvedor Web | PHP - Laravel
2 周I don't think I get the point of post yet. Does it make assertions based on the function's return value?
Software Engineer - C++ trainer
2 周Very clearly articulated ??