Cell get returns a copy so why unsafe?

Hello,

Noob question: Cell::get returns a copy of T so why do we need an unsafe scope in the fonction? Copying T means that we could get a copy from UnsafeCell with no risk at all. At no point we are manipulating memory that is currenly being held or modified by somebody else.

It requires an unsafe block because all calls of UnsafeCell::get require an unsafe block. What you have written is simply an argument that the unsafe block is correct — and not that the unsafe block is unnecessary.

4 Likes

Actually, it is safe, the deref of the pointer is not. But the point is correct.

1 Like

In other words: you know that all you're doing with the pointer returned from UnsafeCell::get() is copying it, but the compiler doesn't know that (it could prove that in this case, but not in other lots of cases). You could also return a reference referencing it, which would be invalid.

1 Like

Right, it's the use of the pointer. The point still stands. It's unsafe because any use of a raw pointer is unsafe.

it's the dereference of the pointer that's unsafe, using a pointer can be perfectly safe:

pub fn f(ptr: *const u8) {
    let mut map = HashMap::new();
    map.insert(ptr, "My Pointer");
    dbg!(map);
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.