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

Viewed 117

I stumbled on this standard library code:

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

How can this work? This seems to be creating a temporary on the stack and then returns a reference to it. Isn't that an obvious lifetime violation?

1 Answers

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

If you read 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,
}

See also:

Related