views:

92

answers:

1

Note: as noted by sellibitze I am not up-to-date on rvalues references, therefore the methods I propose contain mistakes, read his anwser to understand which.

I was reading one of Linus' rant yesterday and there is (somewhere) a rant against operator overloading.

The complaint it seems is that if you have an object of type S then:

S a = b + c + d + e;

may involve a lot of temporaries.

In C++03, we have copy elision to prevent this:

S a = ((b + c) + d) + e;

I would hope that the last ... + e is optimized, but I wonder how many temporaries are created with user defined operator+.

Someone in the thread suggested the use of Expression Templates to deal with the issue.

Now, this thread dates back to 2007, but nowadays when we think elimination of temporaries, we think Move.

So I was thinking about the set of overload operators we should write not to eliminate temporaries, but to limit the cost of their construction (stealing resources).

S&& operator+(S&& lhs, S const& rhs) { return lhs += rhs; }
S&& operator+(S const& lhs, S&& rhs) { return rhs += lhs; } // *
S&& operator+(S&& lhs, S&& rhs) { return lhs += rhs; }

Does this set of operator seems sufficient ? Is this generalizable (in your opinion) ?

*: this implementation supposes commutativity, it doesn't work for the infamous string.

+4  A: 
sellibitze
Matthieu M.