7 ms·
Aliasing is a big one. One of the main reasons Rust’s borrow checker can be painful is that it doesn’t want you to have two mutable references to the same thin
by comex 8y ago
Aliasing is a big one. One of the main reasons Rust’s borrow checker can be painful is that it doesn’t want you to have two mutable references to the same thing, anywhere in your code. In C++, on the other hand, mutable references are the norm, and it’s common to have a multitude of different references to the same object, handed out to any other object that wants to know about it. (And traditionally they wouldn’t even be ref-counted. “Modern C++” encourages the use of shared_ptr, which at least prevents the references themselves from going stale, but that doesn’t help if you have a temporary pointer into a sub-object derived from one reference, e.g. an element of a vector, and then someone invalidates the sub-object through another reference.)
Well, this lifetime checker, to quote the paper, “aims for low false positives in ‘good’ code that follows modern C++ convention”. And for better or worse, that “modern C++ convention” doesn’t include a drastic rework towards Rust-style pervasive immutability and explicit locking (`RefCell`) if you want to mutate something shared. Nor does it do anything magical to work around the reasons Rust needs that. Indeed, there’s not much that can be done as long as you want to stick with a purely function-local analysis (which, for the record, Rust’s borrow checker is as well) – at least, not without using an even more elaborate system of manual annotations.
So instead it gives up on dealing with those cases. Which is perfectly reasonable – it’s still going to do a lot of good by catching many common types of mistakes. On the other hand, it’s important to recognize that its limitations aren’t a matter of a few missing pieces or legacy constraints, things that can be easily patched up in the future. As it stands, the design fundamentally sacrifices the ability to make the kind of complete guarantees Rust’s borrow checker can, and that can’t change unless it’s willing to cause significantly more disruption for codebases and programmers.
- slededit 8y agoI would say modern C++ encourages unique_ptrs and naked pointers for ephemeral references much more than shared_ptr. C++11 invented it after all while shared_ptr has been around longer. Some projects have gone as far as to say shared_ptr is code smell since you never declared who the actual owner is. The memory may not be free’d but that doesn’t mean it isn’t stale.