What would have moved an object allocated in the heap if not pinned

I know that pin is to prevent self-referential objects from being moved in the memory, which could invalidate the content behind the pointers.

To my knowledge, one of the cases when moving in memory happens is when ownership changes:

  • if an object is allocated in the stack, then it'd be a memcpy to move the object from stack frame to stack frame (I guess)
  • however, if the object is allocated in the heap, e.g. behind a smart pointer (Box, Rc, etc), why would move still be needed?

The question is more whether it is possible, not whether it is needed. And it is possible, for example: Rc::into_inner.

1 Like

Vecs may need to move their contents when they reallocate to grow, as one example.

std:mem::swap (and friends) is an example where some values will get moved without the owners giving up their borrowed objects.

And this is also very salient: remember that rustc must prove that safe code cannot trigger UB. "I can't think of why someone would..." isn't good enough.

3 Likes

Ah right!
I was aware that std::mem could do this but wasn't able to think of any other cases like Vec.
Thank you!