by dataflow · 5d ago · 0 comments
I don't understand why that's bad. What's wrong with letting users decide if they want safety or not?
This is known as an ODR-violation, where the same function is compiled with two or more definitions, and there's no rule in C++ to pick which definition should be used. One way to resolve this would be to introduce a rule to pick between these definitions (always pick the function with the contract check disabled, or pick with it enabled), but no one could agree on which rule to use and even if they did it would not work for shared libraries.
There is no doubt that once contracts get standardized, compilers will offer a flag to disable them categorically, ie. disable all of them across all definitions. That won't be an issue because then all definitions will be consistent. But the original proposal allowed flipping contracts on or off per "source-file" with the hopes that developer discipline would ensure that people were consistent about its usage.
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).
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.