微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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,}

另见:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。