21

Is box just syntactic sugar or can it be applied to use cases where Box::new is not sufficient? I read somewhere that box is unstable, does that mean I can only use it with the nightly Rust versions?

trincot
  • 317,000
  • 35
  • 244
  • 286
DeBe
  • 491
  • 3
  • 15

1 Answers1

51

Box::new is just a function, like any other function. It is not special in any way whatsoever. It is grubby and smells faintly of very-close-to-the-expiration date cheese.

box is magic and made up ground-up pixies and the dreams of little children. It is dressed in the finest, swankiest clothes and carries with it the faint aroma of freshly cut pine.

When you execute Box::new(e), because it is a function, e must be completely evaluated and constructed before it can start the call. If this means allocating and filling a 500kB structure on the stack, then it has to allocate and fill a 500kB structure on the stack, and then pass that to Box::new, which only then can allocate the space on the heap (which might fail), and then copy that 500kB into the heap.

When you execute box e, because it is wonderful like a cool breeze on a hot summer's day, the compiler can reorder things such that it begins by allocating the 500kB on the heap, and then filling the 500kB structure directly on the heap. And then it's done. No extra copying, no chewing through stack space. No wasted effort if that "allocate on the heap" thing fails to work out.

box is life, box is love; all hail box!

(And yes, as of writing, it's still unstable which means you need a nightly compiler to bask in its radiance. But soon, the dawn will come. Get it? Dawn? Nightly? ... I'll show myself out...)

DK.
  • 55,277
  • 5
  • 189
  • 162
  • Isn't the `box` keyword supposed to cover custom allocations (ie, allocating something *else* than a `Box`) ? Or is it to be replaced by placement `<-` ? – Matthieu M. Feb 04 '16 at 13:11
  • 3
    `box` will support things other than `Box` (*e.g.* `Rc`, `Arc`, *etc.*) via inference. `<-` is the current provisional syntax for *placement*, which is related, but different: `box` creates a new place to put a value and then puts it there, `<-` places a value in an *existing* place (like, say, on the end of a vector). – DK. Feb 04 '16 at 14:09
  • 3
    I enjoyed every part of this answer - I also learned something. – Simon Whitehead Feb 04 '16 at 21:41
  • @DK. ["Placement new" (RFC 809) is no more](https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911) as of April 2018. – Cole Tobin Jun 19 '23 at 14:24