问题描述
我想将 *mut
指针转换为 &mut
引用.
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) };
这有效.但是,如果 &mut
在 unsafe
块之外,代码将无法部分工作.*ptr = foo
不会将 foo
存储到内存 ptr
点,但是 let foo = *ptr
会赋值*ptr
到 foo
的值.
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) };
unsafe { &mut }
和 &mut unsafe{ }
有什么区别?
推荐答案
它本身与 unsafe
无关,而是与块边界有关.
It doesn't have anything to do with unsafe
per-se, rather with block boundaries.
&*ptr
是一个重新借用",它只是重新解释指向新表单的指针.所以你会得到指向同一个对象的不同类型的指针(一个原始指针和一个引用).
&*ptr
is a "reborrow", it's just going to reinterpret the pointer to a new form. So you get different types of pointers (one raw and one reference) to the same object.
&{*ptr}
是完全不同的,因为 {*ptr}
会 强制复制(感谢@harmic 提供资源):
&{*ptr}
is completely different, because {*ptr}
will force a copy (thanks @harmic for the sourcing):
块总是值表达式并计算值表达式上下文中的最后一个表达式.如果确实需要,这可用于强制移动值.
然后它将借用该副本.这意味着你有两个指针指向完全不同的对象.
Then it will borrow that 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.
参见本演示(不使用 mut 指针,因为没有必要演示这个问题)
See this demonstration (not using mut pointers because there's no need to to demonstrate the issue)
更一般的移动,但在这里你指向一个 usize
,它是 Copy
more generally a move but here you're pointing to a usize
which is Copy
这篇关于&mut unsafe { } 和 unsafe { &mut } 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!