Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use operator+= instead of operator+ for concatenating std::string?

Is there a reason that I often see this construct:

std::string myString = someString + "text" + otherString + "more text";

... instead of this (which I very seldom see):

std::string myString;
myString += someString += "text" += otherString += "more text";

Reading the std::string API, it seems to me that operator+ creates a lot of temporaries (perhaps optimized away by compiler RVO?), while the operator+= variant only appends text.

In some cases, the operator+ variant will be the way to go. But when you only need to append text to an existing non-const string, why not just use operator+=? Any reason not to?

-Rein

like image 687
raapeland Avatar asked Apr 28 '15 11:04

raapeland


2 Answers

operator+= has the wrong kind of associativity for you to write code like your second example. For that to do what you want, you'd need to bracket it like so:

(((myString += someString) += "text") += otherString) += "more text";

The alternative, which gives you the readability and efficiency you want, is to use std::stringstream:

std::stringstream myString;
myString << someString << "text" << otherString << "more text";
like image 177
TartanLlama Avatar answered Oct 17 '22 11:10

TartanLlama


See

std::string aaa += bbb;

is similar to

std::string aaa = aaa + bbb;

so at your example will be changed someString and otherString. In usual cases you don`t need worry about temporaries when use operator+ - in release mode all of them will be eliminated (RVO and/or other optimization).

like image 22
AeroSun Avatar answered Oct 17 '22 09:10

AeroSun