Skip to content

Commit 75aee62

Browse files
authored
Merge pull request rust-lang#94 from PieterPenninckx/master
Document lifetime of temporaries in conditions of if and while-expr
2 parents 8cbcecd + feed479 commit 75aee62

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

Diff for: src/expressions.md

+19-3
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,13 @@ The following expressions can create mutable lvalues:
8484
### Temporary lifetimes
8585

8686
When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is
87-
created and used instead. The lifetime of temporary values is typically the
88-
innermost enclosing statement; the tail expression of a block is considered
89-
part of the statement that encloses the block.
87+
created and used instead. The lifetime of temporary values is typically
88+
89+
- the innermost enclosing statement; the tail expression of a block is
90+
considered part of the statement that encloses the block, or
91+
- the condition expression or the loop conditional expression if the
92+
temporary is created in the condition expression of an `if` or an `if`/`else`
93+
or in the loop conditional expression of a `while` expression.
9094

9195
When a temporary rvalue is being created that is assigned into a `let`
9296
declaration, however, the temporary is created with the lifetime of the
@@ -107,6 +111,18 @@ Here are some examples:
107111
method-call. Here we are assuming that `foo()` is an `&self` method
108112
defined in some trait, say `Foo`. In other words, the expression
109113
`temp().foo()` is equivalent to `Foo::foo(&temp())`.
114+
- `let x = if foo(&temp()) {bar()} else {baz()};`. The expression `temp()` is
115+
an rvalue. As the temporary is created in the condition expression
116+
of an `if`/`else`, it will be freed at the end of the condition expression
117+
(in this example before the call to `bar` or `baz` is made).
118+
- `let x = if temp().must_run_bar {bar()} else {baz()};`.
119+
Here we assume the type of `temp()` is a struct with a boolean field
120+
`must_run_bar`. As the previous example, the temporary corresponding to
121+
`temp()` will be freed at the end of the condition expression.
122+
- `while foo(&temp()) {bar();}`. The temporary containing the return value from
123+
the call to `temp()` is created in the loop conditional expression. Hence it
124+
will be freed at the end of the loop conditional expression (in this example
125+
before the call to `bar` if the loop body is executed).
110126
- `let x = &temp()`. Here, the same temporary is being assigned into
111127
`x`, rather than being passed as a parameter, and hence the
112128
temporary's lifetime is considered to be the enclosing block.

0 commit comments

Comments
 (0)