UnsafeCell and Exclusivity

Regarding UnsafeCell, I have a question about how it interacts with a mutable borrow.

I know that we can mutate an object through immutable borrows by using UnsafeCell without violating the aliasing rules. For example, when we want to mutate some object that is immutably borrowed through raw pointers, we need to wrap it with UnsafeCell in order to avoid UB as Rc does. Then I wondered if it is legal to mutate an UnsafeCell object through a raw pointer that is mutably borrowed. Could it be illegal because UnsafeCell is an escape hatch to invalidate immutability?
I once wrote a demo code that implemented the above mutation and ran Miri to check if is considered violation of the aliasing rule, but Miri didn't complain, so I posted this question.

I appreciate your support.

could you provide an example code ? it's a bit hard to follow your explanation

I just wrote the similar code I once had made and ran it, but it seems that I had done something wrong and misunderstood the behavior. Although it was such a short post, thank you for your prompt response!

1 Like

It’s not legal, but there are proposals for a different type that would allow this kind of operation. In fact, the type already exists unstably in std: UnsafePinned in std::pin - Rust

Here’s a little test setup: (playground)


By the way, you can mark a topic as solved by clicking the checkbox-shaped button on any reply that you’d like to mark as a solution. This can also be your own reply.

2 Likes