← Back to context

Comment by jandrewrogers

24 days ago

As someone who writes high-reliability C++ but is completely outside the standards process, I see the issues with C++ Contracts. It isn’t clear that it solves a problem that anyone has in real codebases, especially after C++20 concepts.

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.

    > high-reliability

I never heard this term used with C++ before. Can you explain more? Ideally: Can you give an example snip of code that demonstrates it clearly?

  • Its a set of rules, used by defense software, they are available on the internet

  • Assuming the original commenter is referring to essentially best-practices, defensive C++ like you see at Google and projects like Envoy proxy, and the other reply is prob mixxed up and thinking of high integrity C++ [0],

    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:

      template <typename T>
      absl::StatusOr<double> Percentile(std::span<const T> sorted_values, double p) {
        static_assert(std::is_arithmetic_v<T>, "T must be numeric");
        CHECK(p >= 0.0 && p <= 100.0) << "p out of range: " << p;
        DCHECK(std::ranges::is_sorted(sorted_values)) << "input not sorted";
    
        if (sorted_values.empty()) {
          return absl::InvalidArgumentError("empty input");
        }
    
        const std::size_t last = sorted_values.size() - 1;
        const double rank = p / 100.0 * last;
        const auto lo = static_cast<std::size_t>(rank);
        const std::size_t hi = std::min(lo + 1, last);
        const double result = std::lerp<double>(sorted_values[lo], sorted_values[hi],
                                              rank - lo);
    
        DCHECK(result >= sorted_values.front() && result <= sorted_values.back());
        return result;
      }
    

    (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

    • If you squint hard enough your example does look a lot like Ada pre and post condition contracts (perhaps a bit less ergonomic, at least for someone who hasn't written C++ in a while).

      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).

    • This is a great reply. Thank you for the code snip. It makes a lot of sense to me now. Basically: You need to have pre-conditions and post-conditions.

      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.

Your comment just made me realize contracts is different from concepts (which are basically bounded genetics, right…?)

  • C++ concepts evaluate the properties of types at compile-time. You can inject arbitrary constraints on type properties anywhere in the code including conditional codegen. It is a way of asking if a type “can express this complex set of abstract things or has this enumerated set of properties” with almost arbitrary detail. They are extremely powerful in terms of expressiveness and specialization of code. Insanely good for performance and reliability engineering.

    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.

    • I maintain a codebase that I’ve migrated from C++98 to C++11 and all the way to C++23 and even a bit of draft 26 (the latter for some minor library improvements). Few things made me quite as happy as moving from using SFINAE to using requires clauses and concepts.

      (IMO the single best improvements over the years have been atomics and maybe variadic templates.)

      6 replies →

    •     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?

      [0] https://www.youtube.com/watch?v=yhhSW-FSWkE

      2 replies →

  • Concepts are evaluated compile time and make a lot of TMP more elegant. Contracts are runtime check, akin to assertions.

    Phrased differently, contracts are to concepts what assert is to static_assert.

    • I think the wumpus that's being chased is that contracts COULD evolve into a compile time check. I'd be much happier if they actually caught the wumpus before they start polluting the language with yet another baroquely complicated feature that gets abandoned before it actually becomes useful (e.g. coroutines, and modules). Or just keep it simple and give us a C++-sensible replacement for assert(), and avoid the rest of it. i.e. contract_assert without the word "contract" in it. That would be a nice feature.

      6 replies →

  • A concept is a compile time requirement that bounds templates which are the generics in C++, so you are close.

The problem is that the current design doesn't take into account binary libraries, or what happens when conflicting contract modes are linked together, as contracts aren't reflected on ABI.

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.

I don't understand the controversy or objections, though maybe I'm missing something. This looks like Ada-2012 contracts which evolved from SPARK Ada going back to near-ancient times. They're well accepted I thought. The idea is to standardize the syntax so that static analyzers can check the contracts, like in Ada. I think Rust is getting something similar. It seems important. Maybe the DIS was rejected because there are still disagreements about some details, ok fine. But rejecting the whole feature sounds counterproductive to keeping C++ relevant. Assuming that last is a good thing, of course.

  • Those are evaluated at compile time, C++’s aren’t guaranteed to be, they’re runtime checks.

    • Yes, static checking when available will have to figure into the toolchain so the compiler knows what to do. It's similar with Ada right now.

Huh? Concepts are types of types. Contracts are fancier, structured runtime assertions. What does one have to do with the other? They're nothing alike.

  • They both start with the letter C, have two syllables, and have/had a hard time getting into the standard. If you’re not paying close attention, it’s easy to get them confused.

    • I’ll admit I only learned they were different today. I’d like to think that if I were a regular C++ user I’d be on top of this, though.

  • That’s exactly my point.

    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.

    • I don't buy the idea that in "high-reliability C++" every condition worth checking can be checked statically, not unless you define "high-reliability" vacuously as that set of programs for which the claim is true. Real-world programs have legitimate reasons to verify invariants dynamically, and C++26 contracts provides an improved way to do so.

      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.

      11 replies →

[flagged]

  • > The problem is that a bunch of people who didn't care for them did something very extreme by voting against approving C++26.

    The only extreme and tone deaf thing I see in this story is how contracts proponents were faced with multiple papers demonstrating quite clearly and extensively how they were broken in specification and in form, but still tried to ignore all the criticism and force them through a consensus process in spite of being clearly opposed.

    How does this make any sense? What was the plan here? To blackmail the C++ community to accept a broken feature under threat of the proposal not passing?

    Make it make sense?

    What I want to see is the people who tried to force contacts upon the process in spite of all opposition to come forth and explain their rationale. It was highly absurd and even unthinkable to force a broken feature down C++'s throats with bureaucratic chicanery, and then complain that the same bureaucracy has mechanisms to stop it's abuse. I for one would like to hear an explanation.

    • FWIW, I now completely reject my above comment, which was ignorant and ill-considered. It's unfortunate that I cannot edit or delete it.