C++ pitfalls hard to avoid that are elegantly managed in Rust

To be fair in modern C++ this particular pitfall can be avoided by deleting the copy ctor and only leaving the move ctor available. You can then define an explicit clone method if needs be.

It is true that generating a deep copy ctor by default is a bad default, though.

Other than that, I'm not sure that I agree with the idea that returning reference to locals can be prevented by the use of smart pointers in c++. Using smart pointers changes the ownership semantics of the code and is not always desirable. A code that overuses shared ptr in particular exposes itself to cycles, and adds overhead compared to the reference solution.

To answer the question by taking a step back, I will summon the example of this post of mine, where a single character typo caused undefined behaviour in my C++ code. Rust gives me the guarantee (and the serenity if I may say so) that a typo will never trigger ub in safe rust. This tranquility alone is worth a lot, because maybe it is possible to write memory safe c++, but you have to be constantly on your guard, gauging everything you (and your colleagues) write, detecting every bad pattern, knowing and remembering all bad c++ defaults, for a single mistake can open the ub gate. I prefer using this time I spent chasing wild pointers in c++ to think about my rust code design and look for logic errors (of which many more can be caught statically in rust thanks to the more expressive type system).

7 Likes