Question

Why return by reference for operator chaining?

I've looked at so many answers on SO and the stock phrase is "return by reference to allow operator chaining", but without an explanation I don't see why I can't do it some other way.

For example, this seems to compile on my system and works fine, and the chaining works:

TestClass operator+=(TestClass tc){
    somePrivateValue += tc.somePrivateValue;
    return *this;
}

Where I can also do this:

TestClass& operator+=(TestClass& tc){
    somePrivateValue += tc.somePrivateValue;
    return *this;
}

Excluding the fact the second example doesn't require the copy constructor to be called for TestClass what are the other advantages?

Was it helpful?

Solution

and the chaining works

No, it doesn't.

TestClass a = some_value;
TestClass b = some_other_value;
(a += b) += b;

Now check the value of a, however that's done. Does it reflect being incremented by b twice? Or only once?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top