Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "std::string + char" expression create another std::string?

Tags:

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?

like image 205
LightTab2 Avatar asked Dec 27 '16 22:12

LightTab2


1 Answers

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.

like image 92
Sam Varshavchik Avatar answered Sep 26 '22 17:09

Sam Varshavchik