1

我发现取消引用一个未绑定的原始指针会导致未定义的行为,但我不知道为什么。我发现这Pin解决了我的情况。为什么它不起作用?

操场

fn main() {
    assert_not_eq(&Ref::pinned(1), &Ref::pinned(2));
    assert_not_eq(&Ref::raw(1), &Ref::raw(2)); // test failed
}

struct Ref<T> {
    value: T,
    reference: *const T,
}

use std::pin::Pin;
impl<T> Ref<T> {
    fn pinned(value: T) -> Pin<Box<Ref<T>>>
    where
        T: std::marker::Unpin,
    {
        let mut instance = Pin::new(Box::new(Self::dangling(value)));
        instance.reference = &mut instance.value;
        return instance;
    }

    fn raw(value: T) -> Ref<T> {
        let mut instance = Self::dangling(value);
        instance.reference = &mut instance.value;
        return instance;
    }

    fn dangling(value: T) -> Ref<T> {
        Ref {
            value,
            reference: 0 as *const T,
        }
    }
}

fn assert_not_eq<T: std::cmp::PartialEq + std::fmt::Debug + Copy>(first: &Ref<T>, second: &Ref<T>) {
    assert_eq!(unsafe { *first.reference }, first.value);
    assert_eq!(unsafe { *second.reference }, second.value);
    assert_ne!(first.value, second.value);
}
4

0 回答 0