Skip to content

Commit 40f3ee2

Browse files
authored
Auto merge of #34520 - Manishearth:fix-unsafecell-docs, r=steveklabnik
Clarify UnsafeCell docs; fix #34496 None
2 parents 0a3180b + 3873402 commit 40f3ee2

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/libcore/cell.rs

+19
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,20 @@ impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefM
847847
/// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
848848
/// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
849849
///
850+
/// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
851+
/// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
852+
/// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
853+
/// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
854+
/// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
855+
/// to ensure that no two mutable references obtained this way are active at the same time, and
856+
/// that there are no active mutable references or mutations when an immutable reference is obtained
857+
/// from the cell. This is often done via runtime checks.
858+
///
859+
/// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
860+
/// okay (provided you enforce the invariants some other way); it is still undefined behavior
861+
/// to have multiple `&mut UnsafeCell<T>` aliases.
862+
///
863+
///
850864
/// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
851865
///
852866
/// # Examples
@@ -916,6 +930,11 @@ impl<T> UnsafeCell<T> {
916930
impl<T: ?Sized> UnsafeCell<T> {
917931
/// Gets a mutable pointer to the wrapped value.
918932
///
933+
/// This can be cast to a pointer of any kind.
934+
/// Ensure that the access is unique when casting to
935+
/// `&mut T`, and ensure that there are no mutations or mutable
936+
/// aliases going on when casting to `&T`
937+
///
919938
/// # Examples
920939
///
921940
/// ```

0 commit comments

Comments
 (0)