Search code examples
rustheap-memorymove-semanticsborrowing

Can Box move its contents when the whole Box is moved?


If I Box::new a value, take a pointer to it (the borrow checker won't allow to take a reference, since I'm about to move the box), and then move the Box, can a move of the value (e.g. a reallocation) happen?

I thought that Box just stores the values address, so that moving the Box would only move the address. Is there therefore a reason why borrow checker prohibits moving it when its contents are immutably borrowed?

Playground


Solution

  • No, moving a Box will not move the value in the heap.

    Box makes a guarantee:

    a Box<T> is guaranteed to be represented as a single pointer

    And Rust makes the guarantee that moves are always bitwise copies (if they copy at all).

    Is there therefore a reason why borrow checker prohibits moving it when its contents are immutably borrowed?

    This is covered by: