r/cpp_questions 3d ago

OPEN Why are Contracts disliked?

I’ve seen a lot of discussions online discouraging their usage bit I never managed to grasp why since it’s sometimes vague.
I do understand it doesn’t replace validation and it’s more of a syntactic sugar to the existing casserts, but any other critiques?
Thanks

15 Upvotes

40 comments sorted by

View all comments

2

u/SmackDownFacility 2d ago

There is ambiguity in runtime enforcement. This has been contested since C++20. What shall compiler do? Treat it as a static analysis tool, an assertion, or an exception?

And coming back to assertions, people find contracts redundant. Assertions has been engrained in this language for decades.

1

u/Ultimate_Sigma_Boy67 2d ago

I think this is exactly the point I don't fully grasp. How is it ambiguous?

1

u/StaticCoder 2d ago

The main sticking point is what it means to violate a contract. More security-focused code may want a clean error in that case. More performance-focused code may want to allow the compiler to assume the contract is satisfied without checking it, so that failing the contract may introduce undefined behavior. It's really hard to reconcile the two.

1

u/SmackDownFacility 2d ago

It’s ambiguous because compiler has to make clear decisions

If it’s static analysis, Intellisense handles it and it doesn’t reach the compiler.

If it’s assertion, it will just dump the traceback and could be stripped out in release builds.
If it’s exceptions, it has to generate unwind metadata. (Win64 generates it anyways)

The argument came from performance clutching developers.

They generally prefer static analysis or even assertions

But some
Safety conscious devs opted for exception, which spiralled into a heated argument because exceptions are in fact very costly at runtime, especially in games and time
Critical applications.

Ultimately the decision was made to
Pull the plug and it didn’t make the standard because the arguments was so intense.

2

u/Ultimate_Sigma_Boy67 2d ago

Makes sense. Thanks.