我偶然发现this standard library code :
impl ops::Deref for PathBuf {
type Target = Path;
#[inline]
fn deref(&self) -> &Path {
Path::new(&self.inner)
}
}
这怎么行?这似乎是在堆栈上创建一个临时对象,然后返回对其的引用。这不是明显的终身违规吗?
最佳答案
路径::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,
}
另请参阅:
关于rust - PathBuf::deref() 如何返回对临时对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67289270/