Foo& Bar( int Val )
{
return Foo( Val );
}
Will not work, can not convert Foo to Foo&
Should work, but not a very useful thing to do as local
copy dies immediately.
Should not work, a reference can not bind to a rvalue.
Ok, you're right. I just tried this again in Ch (a C++
interpreter) -- apparently the method wasn't being called
before and so wasn't compiled.
Does not work, same thing, can not convert Foo to Foo&.
Should also work. Something else is going on as that
syntax is compiling fine in my compiler.
Get a new compiler. Once again, you can not bind a
reference to a rvalue.
This is certainly an interesting design decision of C++. I
suspect it was a 'safety' feature built in, but I prefer
languages to be more flexible by inferring as much as
possible from context. What is the danger of binding to an
r-value?
Consider the following code:
int& r = 5;
r = 6;
If I can bind a reference to a value I can also change that
value. But that is not how a reference works, a reference is a
alias for an object not an object on its own. Therefore a
reference can not bind to a rvalue.
That's an interesting example, and a very good reason for not
allowing using an rvalue to initialize a reference. Still, the
original language (pre-1988, roughly, so we're talking about a
very long time ago) did allow using an rvalue to initialize any
reference, with more or less the same semantics which currently
apply when an rvalue is used to initialize a reference to const.
The rule was changed because it was found, in practice, to be
too great a source of errors. IMHO, the real problem is that
there are too many implicit conversions, and that the result of
an implicit conversion is an rvalue; the errors are typically
cases where an implicit conversion resulted in an rvalue when
the programmer expected an lvalue. Things like:
void
increment( int& i )
{
++ i ;
}
int
main()
{
unsigned x = 0 ;
increment( x ) ;
std::cout << x << std::endl ;
return 0 ;
}
which, of course, results in 0.
Ahh. That's very interesting. This is the kind of bkg info I was
interested in.