Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why operator= returns reference not const reference

Tags:

c++

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?

like image 989
outmind Avatar asked Jun 03 '10 20:06

outmind


People also ask

Why do we return references in operator overloading?

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 (+=).

What is the difference between const reference and reference?

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.

Should I always use const reference?

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).

What does the operator return?

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.


2 Answers

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).

like image 83
CB Bailey Avatar answered Nov 15 '22 06:11

CB Bailey


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.

like image 42
Khaled Alshaya Avatar answered Nov 15 '22 06:11

Khaled Alshaya