@@ -84,9 +84,13 @@ The following expressions can create mutable lvalues:
84
84
### Temporary lifetimes
85
85
86
86
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.
90
94
91
95
When a temporary rvalue is being created that is assigned into a ` let `
92
96
declaration, however, the temporary is created with the lifetime of the
@@ -107,6 +111,18 @@ Here are some examples:
107
111
method-call. Here we are assuming that ` foo() ` is an ` &self ` method
108
112
defined in some trait, say ` Foo ` . In other words, the expression
109
113
` 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).
110
126
- ` let x = &temp() ` . Here, the same temporary is being assigned into
111
127
` x ` , rather than being passed as a parameter, and hence the
112
128
temporary's lifetime is considered to be the enclosing block.
0 commit comments