Skip to content

Commit 2da80cf

Browse files
committed
Add a note about scoping differences between *x and *x.deref()
1 parent 7446bf9 commit 2da80cf

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

src/expressions/operator-expr.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ r[expr.deref.safety]
176176
Dereferencing a raw pointer requires `unsafe`.
177177

178178
r[expr.deref.traits]
179-
On non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an [immutable place expression context](../expressions.md#mutability) and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context.
179+
On non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an [immutable place expression context](../expressions.md#mutability) and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context, except that when `*x` undergoes [temporary lifetime extension], the dereferenced expression `x` also has its [temporary scope] extended.
180180

181181
```rust
182182
# struct NoCopy;
@@ -189,6 +189,21 @@ let c = Box::new(NoCopy);
189189
let d: NoCopy = *c;
190190
```
191191

192+
```rust
193+
// The temporary holding the result of `String::new()` is extended
194+
// to live to the end of the block, so `x` may be used in subsequent
195+
// statements.
196+
let x = &*String::new();
197+
# x;
198+
```
199+
200+
```rust,compile_fail,E0716
201+
// The temporary holding the result of `String::new()` is dropped at
202+
// the end of the statement, so it's an error to use `y` after.
203+
let y = &*std::ops::Deref::deref(&String::new()); // ERROR
204+
# y;
205+
```
206+
192207
r[expr.try]
193208
## The try propagation expression
194209

0 commit comments

Comments
 (0)