r/cpp • • Oct 24 '24 • Take My Silver 1

Why Safety Profiles Failed

https://www.circle-lang.org/draft-profiles.html
180 Upvotes

347 comments sorted by

View all comments

Show parent comment

7

u/Nickitolas Oct 27 '24

Well, in the case of the specific sort example, rewriting it does not actually necessarily make the code any safer: It's possible the code is already perfectly fine! Maybe it already satisfies the safety preconditions of the function already. The only problem would be that this hypothetical analyzer would not be able to reason about it, and would preemptively require it to be rewritten. So in some scenarios, it would just be "busywork", changing code to please a static analyzer for no real gain in safety.

And regarding it being "quite easy to fix", we don't actually know that! My guess is in many cases this pattern would be quite hard to fix. The general case we're looking at here, as Sean's post mentions is that

A C++ compiler can infer nothing about safeness from a function declaration. It can’t by tell by looking what constitutes an out-of-contract call and what doesn’t.

and

This is an unsafe function because it exhibits undefined behavior if called with the wrong arguments. But there’s nothing in the type system to indicate that it has soundness preconditions, so the compiler doesn’t know to reject calls in safe contexts.

I assure you there are many such functions outside the standard library. It's not that strange for a function to have some documented invariants that, when broken, trigger UB. And the problem is that an analyzer is, in many cases, not going to be able to figure those out. That's the general problem that this sort example is a concrete example of. So, in a function that is not part of std, the codebase containing it might not even have an alternative function without that invariant already! They might have to rework their API. This might involve an API break for a library, etc etc.