Why C++26 Contracts might not work for all
https://a4z.noexcept.dev/blog/2026/06/03/Why-Cpp26-Contracts-Might-Not-Work-for-All.htmlC++26 contracts are useful, but I don't think they're a universal replacement, or addition, for existing defensive programming checks. Here are some reasons why.
95
Upvotes
95
u/trad_emark Jun 03 '26
contracts are in the standard now, so lets go with it.
the biggest problem now is that a lot of people misunderstand the purpose of contracts (even some of the comments in this reddit thread clearly indicate that).
contracts do not replace your error handling, they do not replace exceptions, they do not replace returning error codes/std::expected, they do not replace errno, or any other error handling mechanism. contracts do not replace your input validation!
the purpose of contracts is to supersede assert, and improve checking of pre/post conditions of functions. they are intended to help programmers to find bugs in their code. repeat with me: contracts do not replace your input validation!
i myself have a fair amount of criticism for contracts, but that is not the point here. i just hope that this will clear some of the confusion, and it should actually answer several points that people bring up with contracts, that in fact are not issues.
23
u/frayien Jun 03 '26
In our project we have two kinds of assertions, ones that are only enabled in debug or checked builds, and ones that are always enabled.
This way we can disable expensive assertions when needed but keep all cheap assertions to improve reliability.
I dont think this is possible with the proposed contracts. Except maybe conditionally enabling them with macros.
Having a single universal global handler is also quite an issue to ensure errors are handled correctly. Especially if you write a library.
5
u/holyblackcat Jun 03 '26
Those seem like minor issues. I'm more worried about ODR violations on mismatching handling modes. Was this somehow solved?
1
u/FrogNoPants Jun 04 '26
The part where they can run twice is the main reason I'd avoid them for now, though if it is demonstrated that popular compilers don't actually do this, then it won't matter and I might use them.
0
u/Beetny Jun 04 '26
FTFY
0
u/meetingcpp Meeting C++ | C++ Evangelist Jun 04 '26
Someone needs to propose signed/unsigned contracts... scnr
1
u/[deleted] Jun 04 '26
[removed] — view removed comment