so I had never really thought too hard about C++'s unique_ptr abstraction, except to be vaguely annoyed that it so obviously failed to enforce anything remotely resembling what its name appears to promise 1/5
Conversation
anyhow, recently I needed to implement a compiler for the language that and I are using for our spring compiler class, and I decided to use C++ and also to take unique_ptr seriously in the implementation 2/5
1
18
the other data structures from the library that I'm using are vector and unordered_map, which I already liked perfectly well, they are both very nice abstractions 3/5
1
15
anyhow, once I understood that unique_ptr meant nothing like its name but rather something like auto_free_pointer, the pieces sort of fell into place and I experienced almost no memory safety bugs while implementing the compiler, nor has afl-fuzz found any so far 4/5
6
4
47
this is all despite my being a thoroughly mediocre C++ programmer. anyhow this story has no real point except that unique_ptr is actually pretty cool and useful, which I had not expected 5/5
11
5
97
Replying to
So good that, in my quite limited understanding of Rust it sounds like everything nontrivial by default is basically a unique_ptr.
2
2
doc.rust-lang.org/std/boxed/stru is the equivalent to a std::unique_ptr<T>.
It doesn't have the concept of a custom deleter since it's not a tool for working with legacy code.
You can write a huge amount of Rust code without ever having a use for Box<T>. It depends a bit on code style.
1
One use case for Box<T> is implementing a tree with each node as an object owned by the parent. Chunks of nodes would work too.
It's the most direct approach but there are alternatives. A node can't reference their parent with this approach and it's not very flexible.
1
1
The other use case is when using traits as objects. It's a lot more common to use enums (sum types) or traits as type bounds on generics. The reason you'd use trait objects over enums is extensibility (not a limited set of types) and it can keep code size smaller than generics.
1
1
It's usually a lot more natural to use enums and generics. I never found many use cases for trait objects when writing application code. It comes up when making a library that needs to be extensible. Could use them simply to reduce code size but you'd usually just need &Trait.
One other thing is that Box<[T]> exists and you can convert it to and from Vec<T> efficiently. Converting to Box<[T]> has to drop the excess reserved capacity. It's a Vec<T> without the capacity field. You'd normally only use &[T] and Vec<T> though. Box<[T]> does exist though.
1


