Re: Revistiing using return value as reference
On Dec 27, 12:49 pm, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-12-27 02:19, johanatan wrote:
On Dec 26, 6:33 am, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-12-26 06:01, johanatan wrote:
On Dec 25, 3:00 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
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.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34