Re: Returned object assigned to reference
Jonathan Mcdougall wrote:
rageratwork@gmail.com wrote:
Alf P. Steinbach wrote:
* Alf P. Steinbach:
* Old Wolf:
Alf P. Steinbach wrote:
* Andrew Ward:
X val() { return X(); }
int main()
{
X & x = val();
What is the lifetime of the object returned by the call to
val()? I would have thought it should be destroyed immediately,
creating a dangling reference, yet the program works, does the
returned object live until the end of it's enclosing scope?
Anything, because this is Undefined Behavior.
Is a diagnostic required?
Undefined Behavior does not require a diagnostic: it's Undefined
what happens... ;-)
Hey, wait, that's true, but the function doesn't return a reference.
So it's not UB, it's simply something that should not compile (i.e.
a diagnostic is required).
I thought this was something that compiled.
I thought this was legal and a temporary copy of X was returned from
val() to satisfy the rhs of operator=(). Is this not so?
No. val() returns an rvalue and it is bound to a non-const reference,
which is illegal. With
X& val() // <-- reference
{
return X(); // <-- rvalue
}
int main()
{
X& x = val(); // <-- ok
}
the assignment would compile (though having undefined behavior), but
then the return statement would not compile (X() is an rvalue, so the
same problem arises). Finally,
X& val() // <-- reference
{
X x;
return x; // <-- lvalue
}
int main()
{
X& x = val(); // <-- undefined behavior
}
would compile fine, but you'd get undefined behavior because val()
returns a reference to a local object (destroyed at the end of val()).
One way to make this work would be to return a reference
[Ahem]... "to return an _object_"
and to assign
it to a const reference,
"and initialise a reference to const with it"
extending the life of X() to match the
reference's:
X val() // <-- rvalue
{
return X(); // <-- rvalue
}
int main()
{
const X& x = val(); // ok, const-ref bound to rvalue
}
To be able to modify the object, you must copy it:
int main()
{
X x = val(); // ok
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask