2011-11-14

C++: Return type of assignment operator

I had a confusion about whether to return with constant reference or non-constant reference from operator=. It seemed clever and practical to return T const&, because of the following faulty reasoning:

T a,b;
a = b = T(100,200,"something");

The fully bracketed form of the second line is:

a = (b = T(100,200,"something"));

So if we return T const& from T::operator=(T const& rhs) it is sufficient for that purpose. And also when we accidentally write something silly like (a = b) = T(100,200,"something") it will help us by giving a compile error.

Reasoning for non-constant return

The nice argument is that there are useful cases when we do want to modify the result of an assignment, for example:

T a,b,c;
// ...
std::swap(a=b,c); // #1
(b=c).Transponate(); // #2
// ...

The strong argument is that many STL containers require their type parameter(s) to fulfill the Assignable[1] concept, which defines assignment operator to return non-constant reference.