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.


Note also that box syntax doesn't even guarantee on heap only (eg in debug), so you can still blow the stack: https://github.com/rust-lang/rust/issues/49733#issuecomment-621666613

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

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


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".


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.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.