Re: assignment operator
"James Kanze" <james.kanze@gmail.com> wrote in message
news:1190576740.459023.306820@k79g2000hse.googlegroups.com...
On Sep 23, 2:30 pm, Erik Wikstr?m <Erik-wikst...@telia.com> wrote:
C++ has different rules than C regarding lvalues. I rather
< suspect that this is related to the introduction of references
< (which make lvalue-ness far more directly observable). In C++,
< you can write:
int a, b ;
int& r = (a = b) ;
int* p = &(a = b) ;
In C, the second line, of course, is irrelevant, and the third
line is illegal.
You're pretty much right about the reason--I happen to have been there when
the issue first came up, so I know the history.
Here's the key question: You have a fragment of code that looks like this:
// ...
x = y;
return x;
Can you replace that code with
return x=y;
without changing the meaning of the program?
In C, the answer is always yes. In C++, the situation is trickier:
int& foo(int& x, int y)
{
x = y;
return x;
}
If = were defined on int objects the same way as in C, then changing this
function to
int& foo(int& x, int y)
{
return x = y;
}
would cause it to stop compiling, because in C, = yields an rvalue.
So the fact that a function can potentially return a reference makes it
necessary to redefine = to return an value.
It turns out that this redefinition is still compatible with C, because it
is impossible to write a C program that is capable of detecting whether =
returns an lvalue or an rvalue.
Once the built-in = operator returns an lvalue, it makes sense for
user-defined ones to behave similarly.
Incidentally, the same reasoning applies to ++x, --x, and x?y:z.