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
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";
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With