Does the expression below create another std::string and then add it to s1?
std::string s1 = "abc", s2 = "xyz";
s1 += s2 + 'b';
Should it prevent this situation (they'd be added to s1 without additional work)?
std::string s1 = "abc", s2 = "xyz";
s1 += s2;
s1 += 'b';
Do these rules apply to "std::string + std::string" expressions as well?
All overloaded +
operators involving a std::string
return a new std::string
object. This is the inescapable conclusion you will reach when you finally decipher the relevant documentation.
As such, in the first example in your question, the +
operator will return a temporary object, which will get destroyed upon completion of the immediately-following +=
operation.
Having said that: a C++ compiler is permitted to employ any optimization that produces identical observable results. It is remotely possible that a C++ compiler might figure out that it is possible to avoid the need to create a temporary object by transforming the first version of the code to the second one, essentially. I don't think that's very likely, but it's possible. There are no observable differences in the results between the two versions of the code, so that optimization is fair game.
But, technically, the +
operation produces a temporary std::string
object.
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