Stable way to prevent moving out of a type


#1

Is there a stable way to prevent moving out of a type while not changing the in-memory representation of that type? I know I can do it in an unstable way with unsafe_no_drop_flag like so:

#[repr(C)]
#[unsafe_no_drop_flag] // safe because Drop impl is empty
struct RestrictedElement<'a>(Element,PhantomData<&'a Any>);

// Prevent moving out of RestrictedElement
impl<'a> Drop for RestrictedElement<'a> {
    fn drop(&mut self) {}
}

Is this possible in a stable way? Are there any proposals to implement this behavior specifically?


#2

Privacy’s one way to do it.

The memory representation issues with Drop should be going away at some point when on-stack drop flags get finished.


#3

Relatedly, there’s this recently-posted neat trick to make an object not movable: