If you were already writing high-reliability C++ then the benefits are difficult to quantify. If you weren’t writing high-reliability C++ then it saves you almost nothing over doing the standard idioms of high-reliability C++ that were already available to you at very marginally more cost. It does standardize expression of it in narrow cases but the payoff seems minimal.
Most of what C++ Contracts delivers is a mashup of what you can already do with constexpr and C++20 Concepts. I like reliability features but this feature, as delivered, looks fairly useless if you already use reliability features. A compelling standard would need to make much deeper guarantees out of the box. And the compiler can already see through most compositions of constexpr and C++20 concepts, which is already very expressive.
C++ Contracts looks a bit like a feature that was designed long before current standard features existed.
[–] drivebyhooting 4 days ago
[–] jandrewrogers 4 days ago
One of the best features to be added to C++ in many years.
C++ contracts are an attempt to bring C asserts into the C++ age. The weakness of C++ contracts is that they are mostly syntactic sugar over C asserts. If you really care about this type of thing, you probably already have a custom C++ assertion framework that is at least as capable if not more.
The promise of C++ contracts is that they can aid formal verification, which would be great. As delivered, it can’t do much more than was already possible, which will inhibit adoption.
[–] amluto 4 days ago
(IMO the single best improvements over the years have been atomics and maybe variadic templates.)
[–] jandrewrogers 4 days ago
One thing I give the C++ feature gods credit for is recognizing material deficiencies in systems languages and unapologetically trying to fill those gaps starting with C++11. The addition of atomics, strict variadics, constexpr, lambdas, concepts, lifetime annotations, etc has been transformative for C++.
[–] aw1621107 3 days ago
Say what!?
[–] throwaway2037 4 days ago
> the single best improvements over the years have been atomics...
Of course, libatomic and friends have existed for a long time. Real question: Do you feel that the standardisation of atomics within the C++ base library is a material advantage over using libatomic? Also, maybe there are atomic APIs in the C++ base library that are better than libatomic. If so, please kindly share an example or two. I would like to learn more.EDIT
I forgot to give a hat tip to your big upgrade from C++98 to C++23. In some projects, that can require an enormous amount of effort! Can you share a "stories from the trenches" that were difficult in that upgrade?
[–] bluGill 4 days ago
Atomics could work that way. However many other things cannot - we knew modules were a good idea, but they are a everything on a project must use them before anyone can benefit and so they were forever doomed to not be in widespread use until there is a standard. Even today we see adoption is slow because while there is a standard that works everybody is waiting on some other part to adopt before they can get any benefit. (and those who need to go first see the least benefit), but there are signs that things are moving.
[–] pocksuppet 4 days ago
[–] Shorel 4 days ago
[–] AlotOfReading 4 days ago
The weakness of C++ contracts is that they are mostly syntactic sugar over C asserts.
The sugar is actually one of my issues with them. The evaluation semantics are much more complicated / potentially slower than C asserts because of the sugar, and why you would have to pay those costs isn't obvious at first glance. Lisa Lippincott's excellent talk on the design of contracts [0] is what switched me from a sort of neutral support to disliking it. I think it's a stupid place for the national bodies to draw the line though. std::regex is acceptable, but a nothingburger like contracts tanks the vote?[–] jandrewrogers 4 days ago
I think the risk is that C++ contracts become an evolutionary dead-end that hang around forever in code bases because they were standardized. It wouldn’t be the first time this has happened.
[–] randomNumber7 4 days ago
[–] stingraycharles 4 days ago
Phrased differently, contracts are to concepts what assert is to static_assert.
[–] rerdavies 4 days ago
[–] bluGill 4 days ago
[–] MFHava 4 days ago
[–] rerdavies 3 days ago
C++20 provides the language feature only, and none of the libraries to use the feature. You can write your own library to use the C++20 feature, but the standard APIs are raw and brutally complex. There are 3rd party libraries to use coroutines, but they are not part of the C++20 standard.
C++23 provides a std::generator, which is indeed a great feature.
Finally, C++26 provides std::execution, and std::task, which finally makes the feature usable with only standard C++ feature, and provides facilities for executing coroutines on thread pools, or message pumps. Significant features and problems have been deferred to C++29.
I guess it's a fair point that coroutines have not been abandoned. But it's alarming that it will now take the better part of a decade for the feature to reach a sensible state (depending on how C++26 gets handled).
[–] MFHava 2 days ago
I wouldn't put it that way, but I've written several coroutine wrapper types at this point, so my perspective is certainly not objective here.
> Finally, C++26 provides std::execution, and std::task, which finally makes the feature usable with only standard C++ feature, and provides facilities for executing coroutines on thread pools, or message pumps. Significant features and problems have been deferred to C++29.
I remain unconvinced mere mortals will use std::execution.
It's a marvellous example of proving what is possible with TMP without needing language support.
Naturally, it's template hell - heck, the main designer even wrote a Visual Studio Extension to understand the cryptic error messages it can generate.
Apart from that: it interacts badly with Coroutines. Even though the author of std::execution::task reached quite a good design (there are some warts, some of which could only be fixed by delaying to C++29 as it needed a change to the language feature), std::execution has poor support for it - which is unsurprising as key features of coroutines (like symmetric transfer) are not even discussed in P2300...
[–] rerdavies 2 days ago
[–] mikepurvis 4 days ago
[–] YuechenLi 4 days ago
[–] rramadass 4 days ago
[–] pjmlp 4 days ago
Additionally they offer very little mechanisms versus Eiffel's original design, Ada/SPARK or Frama-C.
A basic MVP, expected to improve on subsequent C++ version, assuming that the proposal authors stick around for those evolution proposals.
[–] throwaway81523 3 days ago
[–] steveklabnik 3 days ago
[–] throwaway81523 3 days ago
[–] quotemstr 4 days ago
[–] taybin 4 days ago
[–] moomin 4 days ago
[–] jandrewrogers 4 days ago
Contracts notionally offer the ability to lift some runtime assertions to compile-time. That is how it was sold. Except they don’t in practice.
Meanwhile, concepts + constexpr if used artfully deliver that in practice, including for many cases that contracts were supposed to solve.
I push all verification to compile-time to the extent possible.
[–] quotemstr 4 days ago
While the C++26 variant of contracts doesn't provide the benefits of its static-analysis-centric ancestor from 2014, and therefore isn't as consequential a feature, it still provides value to some and is absolutely not important enough to be worth killing a standard. Concepts do not provide this value.
In any case, it's simply false that C++26 contracts are unnecessary because we have concepts, yet this claim is the thrust of your initial comment.
[–] jandrewrogers 4 days ago
Contracts were sold with the idea of aiding compile-time verification, a noble purpose. The combination of concepts + constexpr allows you to do deeper compile-time verification today by other means than contracts can check. It isn’t obvious that this will ever not be the case. This means contracts is relegated to being another flavor of C asserts.
C++26 contracts are arguably unnecessary because we can achieve the same results other ways, sometimes with stronger properties. I’m a proponent of features that clean up the syntax but C++ contracts look like a nod to people that still use legacy C asserts. That’s fine but it also perpetuates an inadequate model of what assertions should be capable of expressing.
People figured out how to do with C++20 better than what contracts promised.
[–] quotemstr 4 days ago
> People figured out how to do with C++20 better than what contracts promised.
What contracts used to promise is irrelevant. The contracts on the table modernized runtime assertions and are irrelevant to concepts, constexpr, and related facilities.
Is the contracts feature more useful than C's assert()?
If you want to argue that we're better off with the old macro, do so directly. Concepts, in this context, amount to irrelevant distraction.
[–] jandrewrogers 4 days ago
Why would anyone that already ditched C asserts use C++ contracts when it can’t express what the alternatives already can? This isn’t a new problem. People were creating more expressive assertion replacements than contracts offers a decade ago.
C++ contracts are nerfed. It is less expressive and capable than what anyone that cares about these things already uses. So who is expected to use it?
[–] rramadass 4 days ago
You have not understood the C++26 contracts proposal.
It introduces three new syntax viz. "Pre" and "Post" in function signature declaration and a separate "contract_assert" which you can use anywhere in the code path.
It is the "Pre"/"Post" that is useful here. Since it is part of function signature declaration, a static analyzer can easily make sure that all function calls satisfy the contract else you get warning/error. The compiler on its part can inject appropriate code at the function boundary points to do runtime checking etc.
You cannot do this with assert macros. If you wanted something like this earlier, you would have had to change the compiler to emit modified function prologue/epilogue and build your own contract framework which few people had the capability to do.
You can now see the immediate benefits particularly for standard library (and other) code hardening needs. Many UB circumstances can be easily flagged at compile time without too much complexity.
Finally, note that if you use compile-time switch "ignore" to turn-off everything, only the runtime checks are elided (so you do not lose any performance) but the static analyzer can still catch all possible inconsistencies at compile-time thus giving you the best of both worlds.
[–] rramadass 4 days ago
Do you have any information as to why they shifted the focus from static analysis to runtime checks? I only remember that it was based on some Microsoft annotation language or something.
[–] bluGill 4 days ago
Already the compiler is allowed to refuse to compile any code if it would guaranteed fail the contract. The next step is to see how far we can go with that static analysis and what those static analysis tools need to be better. However, this requires people having contracts in fairly widespread use so they can start trying their new ideas to see what happens when they hit the real world.
[–] rramadass 4 days ago
See my comment here - https://news.ycombinator.com/item?id=50361418
However, i also understand the reasoning behind this C++26 contracts proposition - https://news.ycombinator.com/item?id=50364593
While i understand the rationale here, i can also see the problems it might lead to in the future. Correctness concerns should be an all-or-nothing proposition, you cannot do it piecemeal. Hence whether you want to call it "profiles" or not, i would like a Eiffel/Ada-SPARK like system which gives me complete static compile-time analysis and verification along with separate run-time guarantees.
The contracts committee should go back to the drawing board and come up with a more comprehensive solution.
This is a real chance to finally realize the "Safe C++" dream! Ada did it and so can C++.
[–] throwaway2037 4 days ago
[–] zaphirplane 4 days ago
[–] Rexxar 4 days ago
[–] Maxatar 3 days ago
[–] arein3 4 days ago
[–] weitendorf 4 days ago
I wrote a comment explaining what in my mind distinguishes "high reliability" (defensive programming and making invariants/error cases/intended use explicit) C++ from regular C++. IMO it basically boils down to contemporary "Google/fintech style C++", which is a different development culture and ecosystem from defense/automotive
[–] fpoling 4 days ago
[–] NSUserDefaults 4 days ago
[–] Cthulhu_ 4 days ago
(I'll just pre-empt that if you say "Rust", Rust wasn't around until recently and the F-35 project started in '93. These things span decades, while only a few programming languages do)
[–] LiamPowell 4 days ago
[–] fpoling 4 days ago
[–] tialaramex 4 days ago
Bjarne's 2005 JSF rules have the same effect as an "Employees must wash hands" sign. It's not the billion dollar fast food chain's fault that a minimum wage employee didn't obey the sign and now you've got food-borne illness. They put a sign up!
[–] pjmlp 4 days ago
[–] SolarNet 4 days ago
Boeing and other defense contractors dropped it because C++ programmers were cheaper on paper (not realizing/caring that good C++ engineers were more expensive).
[–] cestith 4 days ago
[–] amelius 4 days ago
This also sounds pretentious ...
[–] NSUserDefaults 4 days ago
[–] fps-hero 4 days ago
The only other legitimate choice for writing software at the time would have been ADA, which for some reason never took off despite being purpose build for the application. Of that time, C++ was the new hotness, it was popular, it was solving architectural problems, and it was performant, unlike say Java.
It’s fairly naive to say “I’d never use C++”. The C++ programmers of the time would have looked at Fortran or COBOL with the same level of disdain. We are lucky to live in a time of better options, and the impending post code future.
[–] tialaramex 4 days ago
Ada makes a lot more sense for this work than C++ did twenty years ago.
[–] NSUserDefaults 4 days ago
In today's terms, that's like vibecoding a Mars mission vehicle just because it's "cool".
[–] drysine 4 days ago
What do you mean?
[–] AnimalMuppet 4 days ago
[–] pjmlp 4 days ago
[–] rerdavies 3 days ago
e.g. https://responsiblestatecraft.org/f-35-failure/
[–] throwaway2037 2 days ago
[–] fps-hero 1 day ago
The F35 program certainly seemed like a white elephant, until it crossed the threshold into production and wasn’t. It was a massively delayed cost blowout project, which has turned into a huge success.
[–] AdamN 4 days ago
[–] weitendorf 4 days ago
Here's an example that uses compile time type assertions (static_assert, C++ can already do this), runtime errors (CHECK, standard Google/abseil practice for explicitly handling invalid states and invariants), test/dev checks (defensive programming, basically an inline test), and wrapper/error handling types to do what you might want contracts to do:
(function impl is AI, only need it as scaffolding to demonstrate the contract-adjacent, non-implementation code)Before I was exposed to this style of C++ and learned to write it, C++ basically felt like a different language. People say that the C++ standards committee and language designers have different priorities and developer culture vs most big tech companies/finance and I think it's because even if they're aware of the features and tools that come out of Google (et al) [1], they don't use them in their current day to day jobs and want that functionality in the core C++ toolchain.
IMO, a lot of what they want to add is already "solved" by third party tooling, but because for whatever reason they don't use those as part of their everyday work, they sometimes come up with language features that overcomplicate or solve the wrong thing, in a way that you would intuitively understand if you were already regularly using the 3P tools that solve them.
I could also be the one misinterpreting things here so apologies if this is obvious or not what the original commenter meant by "high reliability".
[0] https://en.wikipedia.org/wiki/High_Integrity_C%2B%2B
[1] https://abseil.io/about/ one of many third party ways to make C++ less insane
[–] pedro_caetano 4 days ago
At this point the rust contracts crate with requires/ensures looks like a more straightforward approximation of Ada's Contracts and assertion policy. But still as far as I am aware no one has implemented something that mimics the static proof functionality in Ada's SPARK subset (which arguably not all applications or problem domains actually need or can justify the extra effort/cost).
[–] rramadass 4 days ago
https://news.ycombinator.com/item?id=50364593
[–] weitendorf 4 days ago
Because it's hard, or not possible, for the same reason that most of these preconditions aren't generally statically verifiable.
Suppose your precondition is x > 5. Statically, you can stop someone from directly passing a literal <= 5, detect locally declared variables assigned to numeric literals and do the same. But to generally infer whether any argument satisfies specific properties quickly gets extremely complicated, because how can you generally verify that the calculations done to a const or literal within the caller's scope guarantee certain properties about the output, without actually performing the calculation? You can come up with cases where you only add to an int and you see it was initialized to 0, so you know it's never < 0 barring underflow. Those are the easy cases
If the caller is passing in something derived from their own arguments, or from I/O, all bets are off. All you know is that the argument has a type, and its value was derived from unknown inputs. So you need a runtime check to actually assert your precondition and make it behave like a type check. But then what happens if input doesn't meet the precondition? Do you throw an exception or crash?
I think that there should be a reference implementation for a useful static analyzer for preconditions, for it to be added to the language. Obviously it would be nice if you could verify that callers only pass in x > 5 to your function, but I think deferring the semantics for contracts to however the build/compiler chooses to handle them (because they might, one day) is not good enough for adding a new feature and syntax to a language. If preconditions can be used for useful static analysis beyond what static asserts and the type system gets you already, there should be evidence for that. I'm skeptical that you can do any better than a regular static assertion/type checks.
Also, I do think the lack of explicit handling (if in practice preconditions are only generally evaluable at runtime) in the contracts syntax is bad. The proposed syntax looks too much like a type or static assertion for a runtime check (note that you can easily see what CHECK/DCHECK macros actually do just by clicking through to their definition). And if it isn't in practice just a runtime check, there should be proof!
[–] William_BB 4 days ago
This is the part of contracts that I don't understand. I suppose you could (1) runtime validate any user input to the program and then (2) chain multiple functions like `safe_sqrt` that provide pre and post conditions.
In theory, this should allow the static analyzer to reason about any arbitrary input. However, this to me raises even more questions: is this practical, is this possible and why would I not try to achieve the same through types ("make invalid types unrepresentable"). Maybe I'm completely off the mark here.
[–] weitendorf 3 days ago
If they can't, then it is IMO a mistake for the language to make contracts declarative (like types), or to think of the static checks as anything more than something extra on top of what is actually a runtime check. And if they can, then why are they not just types?
Bad idea to assume "someone will write static analyzers", and use that to justify a language feature capable of expressing much more complex logic than any static analyzer would be capable of handling.
[–] rramadass 3 days ago
See also my comments here - https://news.ycombinator.com/item?id=50365641 and https://news.ycombinator.com/item?id=50375318 (this one explains how static analysis works which is the confusion i see above).
The idea of a "proof" which is what Symbolic Execution by a Static Analyzer does is different on both sides of the above isomorphism. You cannot mix them indiscriminately. This is because C++ does not have a typing theory (in the sense of lambda calculus derivatives) but simply maps types to sets. Hence one cannot do "Type-Driven Design" natively like a lambda calculus-based language even though you can do aspects of it via explicit programming techniques (eg. see "Functional Programming in C++ by Ivan Cukic").
That is the reason i suspect contracts in C++ moved away from the original focus on static analysis to managed runtime checks + some static analysis. C++26 contracts are firmly in the Set Theory/Predicate Calculus camp and are not integrated into the Type System.
We need an augmentation of the C++ type system and then a narrowing so we can end up with something like Ada-SPARK (call it "Safe C++"/"Profiles"/whatever).
[–] weitendorf 1 day ago
I didn't mean to claim type systems/static analysis in general are not mathematically sound, but that bolting "static analysis" on to something obviously mathematically unsound doesn't give you actual types. A language allowing you to express new invariants and runtime guarantees it can't enforce (not just because they're unimplemented, but because what an implementation would need is not even expressible) is more inconsistent than one where you can't make unenforceable claims
You basically need a complete LEAN-style predicate calculus to generalize guarantees on runtime invariants through compile-time analysis. You are making claims on the interior structure of data that is defined by how many bits of information it encodes, including at the boundary where provenance ends (the arguments passed into your binary are all basically just multiples of 4/8byte enums, ints, strings, or floats), where you'd also need to be able to check/enforce that the data has particular properties, otherwise all you did was introduce more ways to do UB
C++ has nothing close to this in place and it's in fact quite a different claim that any particular invariant is obviously statically verifiable, or that a large class of assertions would be very easy to prove statically, than the claim it would be fine to only catch "most" or even "many" type assertions statically and just handle the rest at runtime.
It's like saying "well 2 + 5 obviously < 10 and most static checks are obvious, so it's better to at least handle that even if we can't statically prove which particular subset of N have 2^N % 10 = N and just check the really hard stuff at runtime". Because that means you have to ask whether any runtime failure is some emergent/adversarially difficult problem from number theory, but at least you can catch all the easy stuff you would have caught anyway
[–] throwaway2037 2 days ago
In the code sample above, can you explain why DCHECK is used instead of CHECK? I needed to Google to ask about those macros, but it looks like DCHECK is only enabled in debug builds.