On Nov 26, 11:00 pm, (e-mail address removed) wrote:
Scope is not the same as lifetime, scope refers to an object's
visibility.
To a symbols visibility. Scope doesn't concern objects, but
symbols (and it's purely a lexical concept, not runtime---except
when language rules associate lifetime with scope).
A temporary's lifetime is ephemeral unless it is kept alive
somehow.
A temporary's lifetime is until the end of the full expression,
normally.
It changes everything. Myclass() generates a temporary with a
lifetime limited to its short existance.
Myclass& r = MyClass(); // temporary is born and dies here
// accesing r is now undefined behavior
a const reference extends the lifetime of the temporary
I think you're missing the point. First, the language rules
don't allow initializing a reference with an rvalue unless it is
a reference to a non-volatile const type. That's what's causing
his error. (There is one exception: if the rvalue is a class
type with a user defined conversion to an lvalue type, it is
treated as an lvalue, and the conversion is used.) Lifetime
simply isn't a consideration here. The second point (not
relavent to his example) is that if a reference is initialized
with a temporary, the lifetime of that temporary is extended to
match the lifetime of the reference. This really has nothing to
do with const, except that the situation can't be reached unless
the reference is to a non-volatile const. (This is, IMHO, a
fairly tricky point, and irrelevant to most code anyway.)
const Myclass& r_ = MyClass(); // temp is born and is kept alive
// r_ is still valid here
// the temporary stays valid until r_'s lifetime ends
your example above does exactly the same thing:
No it doesn't. In his case, the lifetime of the temporary is
until the end of the full expression. Longer than the lifetime
of the temporary it initializes. And none of the special rules
ever reduces the lifetime of a temporary.