4 ms·
C++26: Standard Library Hardening Experiments
- pama 1mo ago30 years late, but I will take it. Contracts look useful and less messy than exceptions.
- cenamus 1mo agoThey solve completely different problems though
- tialaramex 1mo agoSuppose your function doodle_widget is supposed to take a Gonzo Widget, but you're worried somebody might call it with a Non-Gonzo Widget and that can't work. Traditionally you write code which checks the Widget to see if it's Gonzo and if not you throw an exception. Callers can pick, for this function in particular, whether to handle the Exception, in which case they get that Exception to look at, or they can "bubble it up" to be handled in their caller, and so on all the way to the top of the program where if it bubbles up it's reported and then exits the program. With Contracts you write a contract for the function with a pre-condition that the Widget is Gonzo. Your users (programmers who might call doodle_widget) can pick: If they fail a contract the program exits immediately reporting a violation ("quick enforce"), it reports the violation via a global contract handler and then exits ("enforce") or it just reports to the handler but doesn't exit ("observe") or finally, they ignore it entirely ("ignore") These just aren't that different. The contract is maybe slightly better because of the enhanced semantic discovery - you could imagine tooling which gives you a yellow squiggly line because your code violates a contract requirement for example, it's definitely not practical to check exception raising that way.
- Almondsetat 1mo ago>Suppose your function doodle_widget is supposed to take a Gonzo Widget, but you're worried somebody might call it with a Non-Gonzo Widget and that can't work. Can't you just use concepts?
- tialaramex 1mo agoNo. Bjarne's C++ 20 Concepts are basically duck typing, you can express that you want a type where we can call the "is_gonzo" function but you can't say that you only want values of that type in which it's true. Obviously you could re-design the software to follow a Rust-style type-state paradigm, have a NonGonzoWidget and GonzoWidget type which both inherit from Widget and now you can have your function take a GonzoWidget - but that's not what my comparison was about and this technique while possible is less common in C++ Edited to add: Actually, I should clarify that concepts have an idea called "modelling" and you can model anything you want, but the problem is that the machine doesn't care. So you can have a concept which models strings being about how awesome Donald Trump is, and the compiler won't and can't check that, but now a C++ program with a string matching that concept and the value "Trump is a moron" is an invalid C++ program, still compiles, still probably works, but your concept wasn't "modelled" so the program was not valid for whatever that's worth....
- jandrewrogers 1mo agoYes, these types of scenarios are commonly handled with C++20 concepts. The main thing contracts do is provide a standardized scaffolding for enforcement.
- jayd16 1mo agoHow do you handle I/O type exceptions with contracts?
- tialaramex 1mo agoYou would absolutely be entitled to write a contract which says there are never I/O problems. It could even make sense in some cases, though often not.
- jsmith45 1mo agoYou wouldn't. But keep in mind that there are multiple kinds of exceptions. Some exceptions, indicate scenarios the caller could reasonably have avoided. This include things like argument bound or null checks. A caller absolutely could avoid these exceptions by doing its own checks. This can be split between checks that the caller really should have done, like not passing null to a function that cannot take null, vs those where baking the relevant knowledge into the caller would be undesirable (perhaps because future versions of the library expect to accept more values). There are exceptions that in theory a caller could avoid, but in practice it is impractical, like an exception thrown by a parser of some complex format if the provided input isn't legal. The only good way to avoid such an exception is to have a non-throwing parser that you can check with, but you probably don't want to parse twice. An alternative interface for the parser might be able to totally avoid the exception, returning either succeeded (with result tree) or fail with error message, but that would be a design choice of the implementor, not the caller. There can be exceptions that indicate a logic bug in the impleentation (things like throwing if some invariant the implementation is in charge of is violated), but more often this is assertions instead. Lastly, you have exceptions that there is no possible way the caller could always avoid. IO exceptions are among these. While you can sometimes do existence, space, or permission checks or similar to reduce the probability of getting certain exceptions, something else could race your app between the check and performing IO, and make them happen anyway. The primary target for contracts are exceptions that callers both could and should have avoided, and the exception/assertion case that is trying to verify the implementation is working as expected. The other categories of exceptions are more or less totally out of scope.
- bluGill 1mo agoThat is one use where either can be used. However contracts cover a lot of other cases (and as the other replies point out contracts are probably the wrong answer here - a concept is your right answer allow someone else to write a new/different Gonzo complaint widget in the fiture). A contract can check cases where have the right type, but something is wrong anyway. If you need a sorted list a contract can check that.... Likewise exception is useful for a lot of things that should not be a contract. Running out of disk space is still a common problem - you do not want a contract that there is enough disk space, this is an error you need to ask how to handle (often the user would free up disk space external to your program and retry a save).
- deleted 1mo ago[deleted]
- Cieric 1mo agoThere is a small hint of it at the end, but I really hope compile time contract assertions become more common. I know some languages like spark, dafny and a few others do it and generate implicit contracts for things like divide by 0. I've been experimenting with my own custom language that do these things and going back to c++ every day at work is actually a slight let down because of it.
- superxpro12 1mo agoi know in the embedded space this would be invaluable. compile time contracts, or compile time abstract base class would enable compile time resolution of virtuals. so then i can do compile-time polymorphism and c++ is suddenly really attractive in the sub 64k memory space. Maybe -flto does this idk. But all the pieces are there.
- bluGill 1mo agoContracts are written such that the compiler can diagnose a detected violation if it wants to. However most contracts realistically need whole program analysis to diagnose and no compiler can do that - you want a separate static analysis for that. (this doesn't exist, but there is hope people start writing those)
- Cieric 1mo agoYou sounds like you have more experience than me in this space (specifically contracts). I'm curious if you have any examples right off hand that would need whole program analysis. I need more examples to throw at my toy language that's not just another lock free work stealing queue.
- bluGill 1mo agoIf I have more experience than you that means you have no experience at all. I've never used contracts in anything (not even a toy). I've been following contracts in hopes that they can be the next step in my quality journey, but I have no real world experience myself. By whole program analysis I mean you need the entire call tree of a function - stopping only when you can validate that the range of values is constrained to legal values. For some functions this is really simple, while for others the whole flow can be thousands of functions.
- steveklabnik 1mo agoOne thing that I'm curious about regarding all of this: I thought all of this stuff landed in C++26, yet we are still getting papers like https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p4334r0.pdf https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p43... > The C++26 draft has not yet had its final ballot This is co-authored by Bjarne, and so I'm sure it's not trivially false, but maybe I am just missing some detail. I know Bjarne was threatening to cast a veto of C++26 over this, but I thought he did not? Anyone who follows the process a bit more than me have some context here?
- bluGill 1mo agoEverybody has their own ideas of what they want from Contracts. C++26 contracts are trying to get a minimal system that everybody can agree on. The current contracts are not good enough for anybody who wants them - but it is good enough that they can start figuring out the details of making all the different factions happy. C++26 contracts are written by people with experience in ADA/SPARK. While we don't have experience in C++ contracts, there is plenty of experience elsewhere. I find it odd that the paper didn't mention Spark at all! The criticism that it is experimental in all compilers is a fact that can never be anything else. Chicken and egg - nobody will make this non-experimental until it is in the standard. There have many small scale experienements with contracts - enough to agree we want to use this on a larger scale but we need it in the standard first.
- maccard 1mo ago> The current contracts are not good enough for anybody who wants them - This is a recurring pattern across large changes to c++. Modules and coroutines both are great examples of this. > but it is good enough that they can start figuring out the details of making all the different factions happy. I don’t think there’s really a plan to make the factions happy, there’s a plan to get X in, say it’s in and then ignore any actual criticism in favor of “it was the best we could do” while pointing at the other groups for not accepting the massive flaws.
- bluGill 1mo ago
- wakawaka28 1mo agoThis seems like great stuff. Some libraries already do this, so why not standardize the behavior (to the extent it can be done)?