PathBuf::deref() return 如何引用临时文件?

How can PathBuf::deref() return a reference to a temporary?

我偶然发现了 this standard library code:

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

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

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,
}

另请参阅: