I was just reminded, when I wrote out an example of bignum addition yesterday as a lesson, why this is more efficient.
The binary +
operator creates and returns a temporary object. With operands that fit into a machine register, this can be zero-cost (at most spilling what was in the destination register before onto the stack), but sometimes, a large data structure will need to be created. And this seems to be template code that might have to implement that use case.
If the left operand can be clobbered, though, +
can be implemented as +=
, overwriting the operand and optimizing away the creation of a new copy.
This coding style strikes me as a bit odd—as I mentioned, +=
has exactly the semantics the programmer seems to want here, so I’m not sure why they don’t use that instead.
+
, insteadinit += *first;
, shouldn't that yield similar performance to the version with move? Is there really a valid case to prefer+
andmove
over+=
or is it just a design decision? – Eulogistic