Hacker News new | ask | show | jobs
by jcranmer 2537 days ago
> But writing safe C++ is much, much, much more complex than than writing okay-ish C++. The way I see it, Rust has basically taken a lot of the best practices required to write sane C++ (e.g. RAII) and formalized them in a way where the compiler can enforce them.

A concrete example that I've run into recently when trying to write C++ code. I figured that, for safety reasons, I needed to make my type be move-only. I then had to spend about two hours trying to figure out why the program was blowing up. The reason was that I was reusing the variable after moving from it, and the compiler never gave any warning (even on -Wall -Werror) telling me that what I was doing was wrong. In Rust, the same situation would be a compiler error.

5 comments

Yep. As much as people extol lifetimes, my personal opinion is that Rust's aliasing rules are its true golden goose. C/C++'s lax approach to aliasing causes a whole host of issues that Rust is able to avoid by being more strict.
Using a moved-from object in C++ doesn't produce any warnings because it isn't an invalid operation. The standard library types make very limited guarantees about the state of moved from objects (generally just that it remains valid to assign to them and that the object's invariants still hold), but even then it's valid to reuse them as long as you first do something that ensures they're in a known state.
Rust and C++ have rather different concepts of moving. A moved-from Rust object is entirely dead, cannot be used, and will not be dropped. A C++ moved-from object is alive as far as the language is concerned, and the destructor will still run. The move operation and the destructor need to cooperate to avoid crashing. This often adds overhead.
C++: null pointers were a mistake, so we're introducing null objects too.
clang-tidy should catch this and warn about it at compile time.

The two hours seems on the high-end, if someone's able to e.g. use ASan and the program is crashing reproducibly.