Insert overloaded C ++ operator

Can / should be overloaded by the operator in order to increase efficiency (response time or something else) if this operator has to be used often?

I want to overload the + operator to add large vectors to my code very often. Hence the question.

+4
source share
4 answers

Ideally, you will comment on your code, and then decide what to do in the line. In fact, the difference is not very important when you decide to embed regular operators that are overloaded.

+7
source

If you add large vectors, then the overhead of calling the function for the plus will be small relative to the time to actually add two vectors. Therefore, labeling the + inline statement is unlikely to improve your overall execution time.

+6
source

Let the compiler decide on the optimization.

The inline is misleading: the compiler can always do what it needs, just like with the old auto (do you remember those days?) And register .

This modern meaning is "defined in the title: discard, if not used, merge if seen more than once."

+4
source

The compiler should automatically perform small functions to automatically create releases. It is much more important to define a move constructor and move a destination. If your arrays are very large and you are performing several operations at the same time, you can also use expression classes to increase the speed of execution.

 template <class left, class right> struct AddExpr { const left& _left; const right& _right; AddExpr(const left& Left, const right& Right) :_left(Left), _right(Right) {assert(left.count() == right.count());} int count() const {return _left.count();} int operator[](int index) const {return _left[i]+_right[i];} }; class Array { int* data; int size; int count() const {return size;} Array& operator=(AddExpr expr) { for(int i=0; i<expr.count(); ++i) data[i] = expr[i]; }; AddExpr operator+(const Array& lhs, const Array& rhs) {return AddExpr<Array, Array>(lhs, rhs);} AddExpr operator+(const Array& lhs, const Expr& rhs) {return AddExpr<Array, Expr>(lhs, rhs);} AddExpr operator+(const Expr& lhs, const Array& rhs) {return AddExpr<Expr, Array>(lhs, rhs);} AddExpr operator+(const Expr& lhs, const Expr& rhs) {return AddExpr<Expr, Expr>(lhs, rhs);} int main() { Array a, b, c, d; Array c = (a+b) + (c+d); //awesome on lines like this } 

This removes all temporary objects and greatly improves cache efficiency. But I completely forgot what is called this technique.

+1
source

All Articles