Contracts in C++26

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.

Tugba Akbal Mahcup

Senior Software Engineer & Process Master @Rohde and Schwarz

2 周

Looks like a great way of implementing robust, readable, light weight APIs ?

回复
Craig Aiken

Senior Staff Engineer/Manager at Qualcomm

4 周

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".

Marcelo Henrique

Desenvolvedor Web | PHP - Laravel

1 个月

I don't think I get the point of post yet. Does it make assertions based on the function's return value?

回复
Arnaud Becheler, PhD

Software Engineer - C++ trainer

1 个月

Very clearly articulated ??

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了