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


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

Answers 2
Added at 2016-12-27 23:12

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?

Answers to

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

nr: #1 dodano: 2016-12-28 00:12

Depends on context. In your code snippet there won't be another object, s2 and 'b' will be appended to already existing s1.

For example in this case:

std::string s1 = "abc";
std::string s2 = "zxy";
std::string result = s1 + s2;

result is new object concatenating s1 and s2

nr: #2 dodano: 2016-12-28 00:12

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.

Source Show
◀ Wstecz