What's the difference between &mut unsafe { } and unsafe { &mut }?

北慕城南 提交于 2020-05-10 12:37:58

问题


I want to convert *mut pointer to &mut reference.

// Both setting a value to ptr and getting a value from ptr succeeds.
let ptr: &mut usize = unsafe { &mut *(VIRTUAL_ADDRESS_TO_ACCESS_FREE_PAGE as *mut usize) };

This works. However, if &mut is outside of unsafe block, the code will not work partially. *ptr = foo will not store foo to the memory ptr points, but let foo = *ptr will assign the value of *ptr to foo.

// Setting a value to ptr fails, but getting a value from ptr succeeds.
let ptr: &mut usize = &mut unsafe { *(VIRTUAL_ADDRESS_TO_ACCESS_FREE_PAGE as *mut usize) };

What's the difference between unsafe { &mut } and &mut unsafe{ }?


回答1:


It doesn't have anything to do with unsafe per-se, rather with block boundaries.

&*ptr is a "reborrow", it's basically going to reinterpret the pointer in a new form. So you get different types of pointers (one raw and one reference) to the same object.

&{*ptr} is completely different, because {*ptr} will force a copy (more generally a move but here you're pointing to a usize which is Copy), then borrow the copy. This means you get two pointers to completely different objects.

The objects have the same value since one's pointee is a copy of the other's, and thus reading seems to work, but writing doesn't because... you're not writing where you think you are.

See this demonstration (not using mut pointers because there's no need to to demonstrate the issue)



来源:https://stackoverflow.com/questions/61605289/whats-the-difference-between-mut-unsafe-and-unsafe-mut

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!