Contracts for C++ Explained in 5 Minutes -- Timur Doumler

CRussia2019_portrait-1-1024x683.jpgContract assertions, introduced in proposal P2900 for C++26, provide a robust mechanism for runtime correctness checks, offering more flexibility and power than the traditional assert macro. This blog post will explore how contract assertions work, their various evaluation semantics, and how they can improve code reliability with preconditions, postconditions, and custom violation handlers.

Contracts for C++ Explained in 5 Minutes

by Timur Doumler

From the article:

With P2900, we propose to add contract assertions to the C++ language. This proposal is in the final stages of wording review before being included in the draft Standard for C++26.

It has been suggested by some members of the C++ standard committee that this feature is too large, too complicated, and hard to teach. As it turns out, the opposite is true: contract assertions are actually very simple and can be explained in just five minutes. In this blog post, we will do exactly this!

As the name says, contract assertions are assertions — correctness checks that the programmer can add to their code to detect bugs at runtime. So they’re just like the existing assert macro, except they’re not macros (which fixes a bunch of problems) and they’re way more flexible and powerful!


contract_assert replaces assert

Our replacement for assert is called contract_assert. Unlike assertcontract_assert is a proper keyword, but it works in the same way:
 
auto w = getWidget(); 
contract_assert(w.isValid());  // a contract assertion
processWidget(w);
 
The default behaviour is also the same: the assertion is checked, and if the check fails, the program prints a diagnostic message and terminates.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.