Should I use operator + = instead of operator + to concatenate std :: string?

Is there a reason I often see this construct:

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

... instead (which I rarely 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 temporary files (perhaps optimized by the RVO compiler?), And the operator+= option only adds text.

In some cases, the operator+ option would be a way. But when you only need to add text to an existing non-const string, why not just use operator+= ? Any reason not for?

-Rein

+6
source share
2 answers

operator+= has the wrong associativity for writing code, like your second example. To do what you want, you need to copy it like this:

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

An alternative that gives you readability and efficiency is to use std::stringstream :

 std::stringstream myString; myString << someString << "text" << otherString << "more text"; 
+7
source

Cm

 std::string aaa += bbb; 

looks like

 std::string aaa = aaa + bbb; 

so in your example someString and otherString will be changed. In normal cases, you don’t need to worry about temporary operations when using the + operator - in release mode they will all be eliminated (RVO and / or other optimization).

+1
source

Source: https://habr.com/ru/post/986130/


All Articles