Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is A+=B preferable to A=A+B in the same way ++A is to A++?

Tags:

c++

In C++, is A+=B preferable to A=A+B in the same way ++A is to A++?

I understand that a "++A" preincrement is guaranteed to be at least as fast as a "A++" postincrement. This is discussed many places including here and here. Likewise, A+=B is expected to be at least as fast as A=A+B, as here.

I was looking at this for ++:

//From https://herbsutter.com/2013/05/13/gotw-2-solution-temporary-objects/
T T::operator++(int)() {
auto old = *this; // remember our original value
++*this;          // always implement postincr in terms of preincr
return old;       // return our original value
}

My reasoning is that in the worst case (probably from complex object types) A=A+B would have to retrieve and store A and add in B before saving it back to the original A location, while A+=B would take B and add it to A directly. Is my reasoning correct?

It is expected that basic types are rearranged as the same at compile time, and that this really only applies to complex objects requiring operator overloading.

Does this extend generically to most imperative languages?

like image 902
MathFromScratch Avatar asked Jun 11 '16 21:06

MathFromScratch


2 Answers

I would say the reasons aren't quite the same. My main reason for prefering A += B over A = A + B is conciseness. A += B clearly states that you want to add B to A. This is especially true if A is a more complex expression:

node_capacities[std::make_pair(node1,node2)] += edge.capacity;

I've never found the performance of A += B to be worse than A = A + B either.

like image 128
Vaughn Cato Avatar answered Oct 13 '22 01:10

Vaughn Cato


The big thing to remember is that C++ have operator overloading which means that te += operator can mean something completely different from what you expect.

The += operator only works as add and assign to if the "destination" class doesn't have an += operator defined for it. Operator overloading also means that e.g x++ can mean different thing depending on what the class instance of x defines for operator overloads.

like image 32
Some programmer dude Avatar answered Oct 13 '22 01:10

Some programmer dude