4

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

DrunkCoder
  • 379
  • 2
  • 9
  • 2
    The contents won't move when you move the box, but it would be impossible to statically guarantee the validity of references if the borrow checker allowed references to the box contents across moves of the box. – Sven Marnach Nov 16 '20 at 08:04
  • @SvenMarnach Yes, but why does it complain when moving the box? Can't the borrowchecker distinguish the box and the data inside it, which is behind a pointer? The pointer address can effectively be copied. – DrunkCoder Nov 16 '20 at 08:16
  • 1
    Edit: I misunderstood the end of your comment. Now I understand it as that the problem might be it doesn't know when will the data be dropped. That prevents is from predicting the lifetime of the reference you take to the contents. What it *can* guarantee is that the reference is valid as long as the box isn't moved. – DrunkCoder Nov 16 '20 at 08:17
  • Exactly. The borrow checker works locally on individual functions. If you move the box, potentially out of the current function, the borrow checker can't reason about the lifetime of the contents anymore. While it is possible to make the borrow checker more general than it currently is, there are theoretical limits to what it will ever be able to proof. – Sven Marnach Nov 16 '20 at 09:05

1 Answers1

3

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366