UnsafeCell:它如何通知 rustc 选择退出基于别名的优化?

问题描述 投票:0回答:1

我正在阅读 rust std doc 并遇到了这一行:

UnsafeCell<T> opts-out of the immutability guarantee for &T: a shared reference &UnsafeCell<T> may point to data that is being mutated. This is called “interior mutability”.

这是否意味着人们可以创建自己的

UnsafeCell<T>
版本并选择退出在
&T
上进行的基于别名的优化?
UnsafeCell<T>
如何通知 rustc 它不应该进行基于别名的优化?是否有一些属性,或者 rustc 编译器是否编写为通过硬编码的内置规则来识别
UnsafeCell<T>

rust unsafe
1个回答
1
投票

你可以自己阅读所有这些,毕竟源代码是免费浏览的。

UnsafeCell
的行为方式如下,因为它被声明为 实现语言项
unsafe_cell
:

#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
pub struct UnsafeCell<T: ?Sized> {
    value: T,
}

如果您不包含

core
,您可以实现自己的版本,但只能在夜间实现,因为它需要启用 2 个功能:

#![feature(no_core, lang_items)]
#![no_core]
#[lang = "unsafe_cell"]
#[repr(transparent)]
struct MyUnsafeCell<T: ?Sized> {
    v: T
}
© www.soinside.com 2019 - 2024. All rights reserved.