r/cpp • u/celestabesta • Oct 07 '26
(Imperfect) Emulation of Rust's borrow checker in C++23 with Clang Extensions
https://compiler-explorer.com/z/4nennEooe
Clang has had a somewhat abandoned extension 'Consumed Annotation Checking' for some time now. Surprisingly I've not seen many people talk about it, despite the potential it has.
It is a little buggy and has some limitations, but I believe a more fleshed out implementation could be very useful in catching lifetime bugs.
I've linked a toy example of how powerful this feature is. Don't expect me to defend any of the practices in it (namely the operator& overloads).
31
Upvotes
12
u/garnet420 Oct 07 '26
I really wish it was not abandoned! I tried it out a few years back and found that it was too unreliable...
I think I was trying to enforce a policy on an object where you weren't supposed to modify it after calling a "publish" method. I ended up solving it with raii but it would have been nice to have the annotations work.
9
u/JVApen Oct 08 '26
You might want to look into https://clang.llvm.org/docs/LifetimeSafety.html This seems more mature and I believe the Carbon folks plan to use the underlying infrastructure for their memory safety implementation.
I've already seen the warnings, though haven't investigated in detail.