Hacker News new | ask | show | jobs
by zanny 4444 days ago
A lot of this just looks to be lacking const correctness. If you declared most of the mutable types const (and the use cases for a non-const unique_ptr are few) you can avoid most of these issues.

I think it is a valid criticism of the language that not all non-primitive types aren't implicitly const, though. But you could never implement that without colossal backwards compatibility breakage. Which I guess is fine, since you could just keep a code base an std= behind until you fixed it.

> Use after move: obvious. Undefined behavior.

This I don't have an answer to though. I've always disliked how this isn't a compiler error.

2 comments

You can return out references and still get dangling pointers with const values. For example, you can return an iterator outside the scope it lives in and dereference that iterator for undefined behavior (use-after-free, possibly exploitable as above).

Besides, isn't "C++ is memory safe if you don't use mutation" (even if it were true—which it isn't) an extremely uninteresting statement? That's a very crippled subset of the language.

> If you declared most of the mutable types const (and the use cases for a non-const unique_ptr are few) you can avoid most of these issues

Mutability in Rust is perfectly safe because of the static checks built into the type system – the compiler will catch you if you screw things up.

> you could never implement that without colossal backwards compatibility breakage

I cannot express how important immutability as default is. This prevents the issues that C++ has with folks forgetting to mark things as const. There is also lint that warns when locals are unnecessarily marked as mutable, which can catch some logic errors (I say that from experience).

Also note that I said 'immutability' not 'const'. Immutability is a far stronger invariant than const, and therefore is much safer. It could also lead to better compile-time optimisations in the future. I'm sure you know this, but just in case:

- const: you can't mutate it, but others possibly can - immutable: nobody can mutate it