Why operator = returns a not const reference

The original question is about overloading the operator =, and I like to share my findings, since it was not trivial for me to find them. I can not imagine a reasonable use case (a = b) as an lvalue. Using IRC and google, I found the following article: http://msdn.microsoft.com/en-us/magazine/cc301415.aspx

It contains two examples.

  (a=b)=c

  f(T& );
  f(a=b)

but also a little bad, and I think this is bad practice. The second gives me the same feeling. Could you provide better examples, why should it not be permanent?

+5
source share
6 answers

, X, , , a = b X& ( a - l X b - X).

+11

, . :.

int x = 0, y = 1, z = 2;
(x = y) = z;

AFAIK, - , . .

+8

, :

class A
{
public:
    const A& operator= (const A& a) {return *this;}
};

int main(int argc, char* argv[])
{
    A a1;
    A& a2 = a1;
    A& a3 = (a2 = a1);
}

: : C2440: 'initializing': 'const A' 'A &'

MS VS 2010, ? , = const?

+2

post . , . , , , C, return x=y; , x=y; return x;. ++, -, ( const), .

: , . . - , a T const & , "" , , , , , , , , ( ).

+2

const? , , . .

, :

T &local = t1 = t2 = t3;

local const.

+1

If we look at the three auto_ptr methods a, b, and c, the = operator must return a non-constant reference so that you can perform multiple assignments, since assigning a pointer to another changes the first.

so if we have a = b = c, the following will happen: c is assigned the value b (c changes to zero), the operator returns a link to b, the link returned (b = c) is assigned to a, therefore it is modified to point to null, which is only possible if the link is not const.

0
source

All Articles