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

标签 rust lifetime

我偶然发现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/

相关文章:

rust - 返回对链表元素的引用

c++ - 函数中静态变量的生命周期

rust - 为什么我的生命周期函数调用代码正常或失败?

rust - 静态链接使用 regex_macros 的二进制文件

tuples - 在 Rust 中,如何创建由元组支持的切片?

audio - 开始播放时 rodio 中的连接噪音

javascript - 如何在 borsh-js 中序列化枚举

lambda - 传递和评估防 rust 封闭

rust - 为什么不能在同一结构中存储值和对该值的引用?

multithreading - 如何将对堆栈变量的引用传递给线程?