Hacker News new | ask | show | jobs
by Maxatar 11 days ago
An assert goes into the body of a function (.cpp) like this:

    int foo(int x) {
      assert(x != 0);
      return 1 / x;
    }
Because the assert goes into the source file, its behavior is uniquely determined by how that single source file is compiled, so any calls to foo will get consistent behavior.

Contracts are meant to go into header files (.h or .hpp) like this:

    int foo(int x) pre(x != 0);
Because it goes into the header file, such as foo.h, a source file such as bar.cpp can include foo.h with contracts disabled, while baz.cpp can include foo.h with contracts enabled, which means that there is not one unique and unambiguous implementation of foo.

There is no agreed upon solution on what to do in this case. There are many options, you might think bar.cpp gets one version of foo while baz.cpp gets another, you might think that however foo.cpp gets compiled is the definitive version that all others are required to use, you might think if one source file disables contracts they all disable them... every proposal I listed comes with a very deep and entangled web of issues that ends up having unintended consequences and some very serious and complex trade-offs that are not initially obvious.

As things currently stand, with the C++26 as proposed, doing this is an ODR-violation and is not valid C++. It's not simply undefined behavior, it's illegal, what is technically referred to as an IDR (ill-formed, no diagnostic required).

1 comments

> An assert goes into the body of a function (.cpp)

I think you're forgetting function bodies are often in headers? Both for intentionally inline functions, and also for most templates because they're forced to. We've quite literally had this problem for decades. And even a far more severe version of it where people add NDEBUG-only fields to a class. And also with things like hardening macros, etc. I don't see why this case is suddenly the dealbreaker now. Especially because contacts are supposed to lack side effects, so it shouldn't matter what implementation is picked even if it's totally random.

Typo, I meant non-NDEBUG-only.