In the article about Standard Library hardening, we looked at checks for invalid Standard Library container access and other broken preconditions. I mentioned that those requirements are expressed in terms of “contracts”. But what about our code?

In this post, we’ll explore contracts from C++26. We’ll start with a simple cassert, move the requirement into the function itself, and see how to check results. We’ll also look at declarations and definitions, compiler options, and a few details that can surprise you.

Starting with an Assertion

Let’s start with a small example:

A header file first:

// foo.h
#include <vector>
int get_value(const std::vector<int>& values, std::size_t index);