The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them. I cannot imagine reasonable example to use (a=b) as lvalue. With the help of IRC and google I've found the next article: http://msdn.microsoft.com/en-us/magazine/cc301415.aspx
it provides two examples.
(a=b)=c
f(T& );
f(a=b)
but both a bit not good, and I believe that it is bad practice. The second one give me the same feeling. Could you provide more good examples why it should be non constant?
You would want an expression, a + b , to return a reference to one of a or b, which would have the results of the expression. Thus you would modify one of a or b to be the sum of a and b. So you would want to redefine the semantics of the operator (+) to be the same as the operator (+=).
A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.
Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter. You can always add const, but not take it away (not without a const cast which is a really bad idea).
The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
One good reason is that one of the requirements in the standard for a class X
to be useable in the standard containers is that the expression a = b
must have type X&
(where a
is an lvalue of type X
and b
is an rvalue of type X
).
Most probably because this is how the native types of the language work. e.g.:
int x = 0, y = 1, z = 2;
(x = y) = z;
AFAIK, Dr. Stroustrup said that it is a good thing to have consistency in the language. i.e. user-defined types should behave just like native types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With