What is the scope of unnamed values?

后端 未结 1 783
情深已故
情深已故 2021-01-20 22:39

When do unnamed values go out of scope, when is the value dropped?

I\'m looking for an answer based on official docs, not based on experiments.

相关标签:
1条回答
  • 2021-01-20 23:30

    From the reference:

    When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is created and used instead, if not promoted to 'static. Promotion of an rvalue expression to a 'static slot occurs when the expression could be written in a constant, borrowed, and dereferencing that borrow where the expression was the originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. &None always has the type &'static Option<_>, as it contains nothing disallowed). Otherwise, the lifetime of temporary values is typically

    • the innermost enclosing statement; the tail expression of a block is considered part of the statement that encloses the block, or

    • the condition expression or the loop conditional expression if the temporary is created in the condition expression of an if or an if/else or in the loop conditional expression of a while expression.

    When a temporary rvalue is being created that is assigned into a let declaration, however, the temporary is created with the lifetime of the enclosing block instead, as using the enclosing statement (the let declaration) would be a guaranteed error (since a pointer to the temporary would be stored into a variable, but the temporary would be freed before the variable could be used). The compiler uses simple syntactic rules to decide which values are being assigned into a let binding, and therefore deserve a longer temporary lifetime.

    The reference then has examples of these rules.

    0 讨论(0)
提交回复
热议问题