Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.

Commit f4165f2

Browse files
committed
add example of &T -> *mut T
1 parent 2dc8e90 commit f4165f2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
### Example
2+
3+
```
4+
pub unsafe fn a() -> u8 {
5+
let mut x = 11;
6+
b(&x as *const u8 as *mut u8);
7+
x
8+
}
9+
10+
unsafe fn b(x: *mut u8) {
11+
*x = 22;
12+
}
13+
```
14+
15+
### Explanation
16+
17+
Here the user takes a shared reference `&x` which is then cast to a
18+
`*mut` reference and ater used to mutate the variable `x`. Subtle
19+
aspects here:
20+
21+
- The lifetime of the `&x` reference will be inferred very short (just
22+
the duration of the cast, basically), so from a certain naive POV
23+
`x` is "not borrowed" and yet its value changes.
24+
- The result of `&x` cannot, in safe code, be used to mutate `x`, and
25+
yet its value changes.
26+
27+
Based on either of the above points, one might think the function
28+
above could return `11`, because the compiler might constant propagate
29+
`11` from the `let mux x = 11` to the return value under the
30+
assumption that it cannot change.
31+
32+
### Source
33+
34+
https://github.com/rust-lang/rust/issues/30424#issue-122623932

0 commit comments

Comments
 (0)