Why is it legal to borrow a temporary?

Why is it legal to borrow a temporary? It’s legal for the same reason it’s illegal in C++ — because someone said that’s how it should be. How long does the temporary live in Rust? And since x is only a borrow, who is the owner of the string? The reference says: the temporary scope … Read more

Why lifetime of temporary doesn’t extend till lifetime of enclosing object?

The standard considers two circumstances under which the lifetime of a temporary is extended: §12.2/4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the … Read more

C++ – using const reference to prolong a member of a temporary, ok or UB?

Your code should be well-formed, because for temporaries (emphasis mine) Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference Given A().b[4], b[4] is the subobject of b and the data member b is the subobject of the … Read more

Lifetime of temporaries

A temporary object is destroyed when the full-expression that lexically contains the rvalue whose evaluation created that temporary object is completely evaluated. Let me demonstrate with ASCII art: ____________________ full-expression ranges from ‘b’ to last ‘)’ bar( foo().c_str() ); ^^^^^ ^ | | birth funeral