![](/img/trans.png)
[英]How can I return a reference wrapped by `Option` by implementing `Deref` in Rust?
[英]How can PathBuf::deref() return a reference to a temporary?
我偶然发现了这个标准库代码:
impl ops::Deref for PathBuf {
type Target = Path;
#[inline]
fn deref(&self) -> &Path {
Path::new(&self.inner)
}
}
这怎么行? 这似乎是在堆栈上创建一个临时对象,然后返回对它的引用。 这不是明显的终身违规吗?
Path::new
使用unsafe
代码将&OsStr
转换为&Path
:
pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
}
如果您阅读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,
}
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.