Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UnsafeCell: How does it inform rustc to opt out of alias based optimizations?

I was reading the rust std doc and came across this line:

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”.

Does this mean one can create thier own version of UnsafeCell<T> and opt out of alias based optimizations done on &T ? How does UnsafeCell<T> inform rustc that it should not do alias based optimizations ? Is there some attribute for it or is the rustc compiler written to recognize UnsafeCell<T> with a hard coded built in rule ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can read all of this up on your own, the source code is free to browse after all. UnsafeCell behaves how it does because it’s declared as implementing the language item unsafe_cell:

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

If you don’t include core you can implement your own version, but only on nightly since it requires 2 features to be enabled:

#![feature(no_core, lang_items)]
#![no_core]
#[lang = "unsafe_cell"]
#[repr(transparent)]
struct MyUnsafeCell<T: ?Sized> {
    v: T
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading