{_unsafecell">
当前位置:   article > 正文

Rust 内部可变性之UnsafeCell

unsafecell

UnsafeCell是构建内部可变性Cell、RefCell、Mutex和RwLock的基础。

UnsafeCell在文档中被定义为Rust内部可变性的核心原语。

#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
#[repr(no_niche)] // rust-lang/rust#68303.
pub struct UnsafeCell<T: ?Sized> {
    value: T,
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

看一下这个get()函数,它接收不可变引用,然后将其转换三次。先是原始常量指针 (*const T),然后还是一个原始常量指针,最后是一个原始可变指针 (*mut T),返回给调用者。

#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
pub const fn get(&self) -> *mut T {
    // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
    // #[repr(transparent)]. This exploits libstd's special status, there is
    // no guarantee for user code that this will work in future versions of the compiler!
    self as *const UnsafeCell<T> as *const T as *mut T
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/909625
推荐阅读
相关标签
  

闽ICP备14008679号