lundi 31 août 2015

Is overloading the addition operator with an rvalue reference as its left hand operand considered as a good practice?

Assuming stris a class for storing string values, it would overload the addition operator in order to support string concatenation. Like this:

str operator+(const str &a,const str &b);

But the problem is if we have something like this:

str s=str("Hel") + str("lo ") + str("Wor") + str("ld!");

Then it would create 3 temporary objects (as we get a new object in every addition) which aren't really needed in this context. A simple solution to this problem may be overloading a new addition operator which accepts a rvalue-reference as its left operand and returns this operand also as a rvalue-reference after concatenating it with the right operand. Something like this:

str &&operator+(str &&a,const str &b){
   a+=b;
   return std::move(a);
}

By having overloaded this operator, then the mentioned statement would just create a single temporary object and following additions will just be concatenated to that temporary object.

My question is, is this method a correct solution for this problem?

Aucun commentaire:

Enregistrer un commentaire