Why not another keyword like 'unbox' for heap memory deallocation?

AFAIK, box_syntax is used to achieve direct heap allocation in a pluggable way thru lang items and thus with less compiler magic. so my naïve thought is why not another keyword for the opposite operation free to reveal more compiler implementation details to user? boxed.rs - source here only one explicit comment is confusing here.

I would rather just have less magic. It can be implemented by calling the std::alloc::dealloc method.

8 Likes

Note also that box syntax doesn't even guarantee on heap only (eg in debug), so you can still blow the stack: Tracking issue for box_syntax · Issue #49733 · rust-lang/rust · GitHub

(Oops, sorry, replied to the wrong comment!)

Note that these have all been unaccepted, and thus should not be treated as precedent:

2 Likes

Meanwhile, Box<T> is still special in that you can dereference to move values out, even when they're !Copy, and this will also free the allocation. This is what I would think of as "unboxing".

6 Likes

then I'm confused about the impl of Box::new here , why box is used here still?

Because no maintenance has taken place yet to remove it.

Thks. I get ur point as this Extending deref/index with ownership transfer: DerefMove, IndexMove, IndexSet · Issue #997 · rust-lang/rfcs · GitHub explains, Box is special in how "deref" (explictly * or auto-deref) is performed.

thks, it explains.

Furthermore, Box is not the only way to perform heap allocation in Rust. There are many other types (e.g. Rc, String, etc.) that also heap-allocate. Calling heap deallocation "unboxing" would thus be misleading.

Furthermore, there's no real justification for making heap allocation into a language feature even if Box is special w.r.t. Deref. It could just use Layout::allocate()/Layout::deallocate() and a raw pointer/NotNull<T> – the allocation part is not part of the special behavior of Box.

5 Likes