Skip to content

Commit 242118b

Browse files
author
Pieter Penninckx
committed
Document lifetime of temporaries in condition expression of if-expr
Explain that temporaries created in the condition expression of an if or if/else are dropped immediately after the condition expression.
1 parent 2c29398 commit 242118b

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

src/expressions.md

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,20 @@ created and used instead. The lifetime of temporary values is typically the
8888
innermost enclosing statement; the tail expression of a block is considered
8989
part of the statement that encloses the block.
9090

91-
When a temporary rvalue is being created that is assigned into a `let`
92-
declaration, however, the temporary is created with the lifetime of the
93-
enclosing block instead, as using the enclosing statement (the `let`
91+
A first exception is when a temporary value is created in the
92+
condition expression of an `if` or an `if`/`else` expression.
93+
In this case, the lifetime ends right after the condition expression.
94+
95+
Here is an example:
96+
97+
- `let x = if foo(&temp()) {bar()} else {bas()};`. The expression `temp()` is
98+
an rvalue. As the temporary is created in the condition expression
99+
of an `if`/`else`, it will be freed at the end of the condition expression
100+
(in this example before the call to `bar` or `bas` is made).
101+
102+
Another exception is when a temporary rvalue is being created that is assigned
103+
into a `let` declaration. In this case the temporary is created with the
104+
lifetime of the enclosing block, as using the enclosing statement (the `let`
94105
declaration) would be a guaranteed error (since a pointer to the temporary
95106
would be stored into a variable, but the temporary would be freed before the
96107
variable could be used). The compiler uses simple syntactic rules to decide

0 commit comments

Comments
 (0)