PathBuf::deref() 如何返回对临时对象的引用?

问题描述

我偶然发现了 this standard library code

impl ops::Deref for PathBuf {
    type Target = Path;
    #[inline]
    fn deref(&self) -> &Path {
        Path::new(&self.inner)
    }
}

这怎么工作?这似乎是在堆栈上创建一个临时文件,然后返回对它的引用。这不是明显的终生违规吗?

解决方法

Path::new uses unsafe code to convert an &OsStr to a &Path

pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
    unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
}

如果您阅读the internal documentation for Path

// `Path::new` current implementation relies
// on `Path` being layout-compatible with `OsStr`.
// When attribute privacy is implemented,`Path` should be annotated as `#[repr(transparent)]`.
// Anyway,`Path` representation and layout are considered implementation detail,are
// not documented and must not be relied upon.
pub struct Path {
    inner: OsStr,}

另见: