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

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

Does a const reference class member prolong the life of a temporary?

Only local const references prolong the lifespan. The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor’s argument n, and becomes invalid when the object n is bound to goes out of scope. The lifetime extension is not transitive through … Read more

How come a non-const reference cannot bind to a temporary object?

From this Visual C++ blog article about rvalue references: … C++ doesn’t want you to accidentally modify temporaries, but directly calling a non-const member function on a modifiable rvalue is explicit, so it’s allowed … Basically, you shouldn’t try to modify temporaries for the very reason that they are temporary objects and will die any … Read more