Re: A non-const reference may only be bound to an lvalue?
"George" <George@discussions.microsoft.com> wrote in message
news:2AC35AF1-DD6E-4A7E-9B83-81203539F863@microsoft.com
Your reply is very helpful. I have performed some further self-study.
In my understanding, rvalue could be in two cases,
1. constant;
2. temporary object (e.g. function return value if the return value
is not a reference -- this is my sample for source() function,
right?).
Sounds about right.
Another question is, why currently the compiler does not allow
binding a non-const reference to an rvalue? What is the internal
reason and benefits/risks behind this rule?
To avoid surprises like this:
void f(long& x) { x = 1; }
int y = 0;
f(y); // hypothetical, doesn't compile
assert(y == 1); // fails
If f(y) were allowed to compile, it would generate a temporary of type
long, and the function would modify that temporary, leaving the original
int variable unchanged.
It would also mean that a seemingly benign change in function
signature( from f(int&) to f(long&) ) may silently alter the behavior of
the program. As things stand now, such a change would lead to compiler
errors - much better than silent behavior change.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925